three.webgpu.js 1.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix2, Matrix3, Matrix4, EventDispatcher, MathUtils, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, InterleavedBufferAttribute, DynamicDrawUsage, NoColorSpace, Texture, UnsignedIntType, IntType, NearestFilter, Sphere, BackSide, DoubleSide, Euler, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, OrthographicCamera, PerspectiveCamera, RenderTarget, LinearSRGBColorSpace, RGBAFormat, HalfFloatType, CubeUVReflectionMapping, BufferGeometry, BufferAttribute, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, LessCompare, RGFormat, BasicShadowMap, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, DataTexture, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, warnOnce, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'aoMapIntensity',
  16. 'attenuationColor',
  17. 'attenuationDistance',
  18. 'bumpMap',
  19. 'clearcoat',
  20. 'clearcoatMap',
  21. 'clearcoatNormalMap',
  22. 'clearcoatNormalScale',
  23. 'clearcoatRoughness',
  24. 'color',
  25. 'dispersion',
  26. 'displacementMap',
  27. 'emissive',
  28. 'emissiveIntensity',
  29. 'emissiveMap',
  30. 'envMap',
  31. 'envMapIntensity',
  32. 'gradientMap',
  33. 'ior',
  34. 'iridescence',
  35. 'iridescenceIOR',
  36. 'iridescenceMap',
  37. 'iridescenceThicknessMap',
  38. 'lightMap',
  39. 'lightMapIntensity',
  40. 'map',
  41. 'matcap',
  42. 'metalness',
  43. 'metalnessMap',
  44. 'normalMap',
  45. 'normalScale',
  46. 'opacity',
  47. 'roughness',
  48. 'roughnessMap',
  49. 'sheen',
  50. 'sheenColor',
  51. 'sheenColorMap',
  52. 'sheenRoughnessMap',
  53. 'shininess',
  54. 'specular',
  55. 'specularColor',
  56. 'specularColorMap',
  57. 'specularIntensity',
  58. 'specularIntensityMap',
  59. 'specularMap',
  60. 'thickness',
  61. 'transmission',
  62. 'transmissionMap'
  63. ];
  64. /**
  65. * A WeakMap to cache lights data for node materials.
  66. * Cache lights data by render ID to avoid unnecessary recalculations.
  67. *
  68. * @private
  69. * @type {WeakMap<LightsNode,Object>}
  70. */
  71. const _lightsCache = new WeakMap();
  72. /**
  73. * This class is used by {@link WebGPURenderer} as management component.
  74. * It's primary purpose is to determine whether render objects require a
  75. * refresh right before they are going to be rendered or not.
  76. */
  77. class NodeMaterialObserver {
  78. /**
  79. * Constructs a new node material observer.
  80. *
  81. * @param {NodeBuilder} builder - The node builder.
  82. */
  83. constructor( builder ) {
  84. /**
  85. * A node material can be used by more than one render object so the
  86. * monitor must maintain a list of render objects.
  87. *
  88. * @type {WeakMap<RenderObject,Object>}
  89. */
  90. this.renderObjects = new WeakMap();
  91. /**
  92. * Whether the material uses node objects or not.
  93. *
  94. * @type {boolean}
  95. */
  96. this.hasNode = this.containsNode( builder );
  97. /**
  98. * Whether the node builder's 3D object is animated or not.
  99. *
  100. * @type {boolean}
  101. */
  102. this.hasAnimation = builder.object.isSkinnedMesh === true;
  103. /**
  104. * A list of all possible material uniforms
  105. *
  106. * @type {Array<string>}
  107. */
  108. this.refreshUniforms = refreshUniforms;
  109. /**
  110. * Holds the current render ID from the node frame.
  111. *
  112. * @type {number}
  113. * @default 0
  114. */
  115. this.renderId = 0;
  116. }
  117. /**
  118. * Returns `true` if the given render object is verified for the first time of this observer.
  119. *
  120. * @param {RenderObject} renderObject - The render object.
  121. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  122. */
  123. firstInitialization( renderObject ) {
  124. const hasInitialized = this.renderObjects.has( renderObject );
  125. if ( hasInitialized === false ) {
  126. this.getRenderObjectData( renderObject );
  127. return true;
  128. }
  129. return false;
  130. }
  131. /**
  132. * Returns `true` if the current rendering produces motion vectors.
  133. *
  134. * @param {Renderer} renderer - The renderer.
  135. * @return {boolean} Whether the current rendering produces motion vectors or not.
  136. */
  137. needsVelocity( renderer ) {
  138. const mrt = renderer.getMRT();
  139. return ( mrt !== null && mrt.has( 'velocity' ) );
  140. }
  141. /**
  142. * Returns monitoring data for the given render object.
  143. *
  144. * @param {RenderObject} renderObject - The render object.
  145. * @return {Object} The monitoring data.
  146. */
  147. getRenderObjectData( renderObject ) {
  148. let data = this.renderObjects.get( renderObject );
  149. if ( data === undefined ) {
  150. const { geometry, material, object } = renderObject;
  151. data = {
  152. material: this.getMaterialData( material ),
  153. geometry: {
  154. id: geometry.id,
  155. attributes: this.getAttributesData( geometry.attributes ),
  156. indexVersion: geometry.index ? geometry.index.version : null,
  157. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  158. },
  159. worldMatrix: object.matrixWorld.clone()
  160. };
  161. if ( object.center ) {
  162. data.center = object.center.clone();
  163. }
  164. if ( object.morphTargetInfluences ) {
  165. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  166. }
  167. if ( renderObject.bundle !== null ) {
  168. data.version = renderObject.bundle.version;
  169. }
  170. if ( data.material.transmission > 0 ) {
  171. const { width, height } = renderObject.context;
  172. data.bufferWidth = width;
  173. data.bufferHeight = height;
  174. }
  175. data.lights = this.getLightsData( renderObject.lightsNode.getLights() );
  176. this.renderObjects.set( renderObject, data );
  177. }
  178. return data;
  179. }
  180. /**
  181. * Returns an attribute data structure holding the attributes versions for
  182. * monitoring.
  183. *
  184. * @param {Object} attributes - The geometry attributes.
  185. * @return {Object} An object for monitoring the versions of attributes.
  186. */
  187. getAttributesData( attributes ) {
  188. const attributesData = {};
  189. for ( const name in attributes ) {
  190. const attribute = attributes[ name ];
  191. attributesData[ name ] = {
  192. version: attribute.version
  193. };
  194. }
  195. return attributesData;
  196. }
  197. /**
  198. * Returns `true` if the node builder's material uses
  199. * node properties.
  200. *
  201. * @param {NodeBuilder} builder - The current node builder.
  202. * @return {boolean} Whether the node builder's material uses node properties or not.
  203. */
  204. containsNode( builder ) {
  205. const material = builder.material;
  206. for ( const property in material ) {
  207. if ( material[ property ] && material[ property ].isNode )
  208. return true;
  209. }
  210. if ( builder.renderer.overrideNodes.modelViewMatrix !== null || builder.renderer.overrideNodes.modelNormalViewMatrix !== null )
  211. return true;
  212. return false;
  213. }
  214. /**
  215. * Returns a material data structure holding the material property values for
  216. * monitoring.
  217. *
  218. * @param {Material} material - The material.
  219. * @return {Object} An object for monitoring material properties.
  220. */
  221. getMaterialData( material ) {
  222. const data = {};
  223. for ( const property of this.refreshUniforms ) {
  224. const value = material[ property ];
  225. if ( value === null || value === undefined ) continue;
  226. if ( typeof value === 'object' && value.clone !== undefined ) {
  227. if ( value.isTexture === true ) {
  228. data[ property ] = { id: value.id, version: value.version };
  229. } else {
  230. data[ property ] = value.clone();
  231. }
  232. } else {
  233. data[ property ] = value;
  234. }
  235. }
  236. return data;
  237. }
  238. /**
  239. * Returns `true` if the given render object has not changed its state.
  240. *
  241. * @param {RenderObject} renderObject - The render object.
  242. * @param {Array<Light>} lightsData - The current material lights.
  243. * @return {boolean} Whether the given render object has changed its state or not.
  244. */
  245. equals( renderObject, lightsData ) {
  246. const { object, material, geometry } = renderObject;
  247. const renderObjectData = this.getRenderObjectData( renderObject );
  248. // world matrix
  249. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  250. renderObjectData.worldMatrix.copy( object.matrixWorld );
  251. return false;
  252. }
  253. // material
  254. const materialData = renderObjectData.material;
  255. for ( const property in materialData ) {
  256. const value = materialData[ property ];
  257. const mtlValue = material[ property ];
  258. if ( value.equals !== undefined ) {
  259. if ( value.equals( mtlValue ) === false ) {
  260. value.copy( mtlValue );
  261. return false;
  262. }
  263. } else if ( mtlValue.isTexture === true ) {
  264. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  265. value.id = mtlValue.id;
  266. value.version = mtlValue.version;
  267. return false;
  268. }
  269. } else if ( value !== mtlValue ) {
  270. materialData[ property ] = mtlValue;
  271. return false;
  272. }
  273. }
  274. if ( materialData.transmission > 0 ) {
  275. const { width, height } = renderObject.context;
  276. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  277. renderObjectData.bufferWidth = width;
  278. renderObjectData.bufferHeight = height;
  279. return false;
  280. }
  281. }
  282. // geometry
  283. const storedGeometryData = renderObjectData.geometry;
  284. const attributes = geometry.attributes;
  285. const storedAttributes = storedGeometryData.attributes;
  286. const storedAttributeNames = Object.keys( storedAttributes );
  287. const currentAttributeNames = Object.keys( attributes );
  288. if ( storedGeometryData.id !== geometry.id ) {
  289. storedGeometryData.id = geometry.id;
  290. return false;
  291. }
  292. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  293. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  294. return false;
  295. }
  296. // compare each attribute
  297. for ( const name of storedAttributeNames ) {
  298. const storedAttributeData = storedAttributes[ name ];
  299. const attribute = attributes[ name ];
  300. if ( attribute === undefined ) {
  301. // attribute was removed
  302. delete storedAttributes[ name ];
  303. return false;
  304. }
  305. if ( storedAttributeData.version !== attribute.version ) {
  306. storedAttributeData.version = attribute.version;
  307. return false;
  308. }
  309. }
  310. // check index
  311. const index = geometry.index;
  312. const storedIndexVersion = storedGeometryData.indexVersion;
  313. const currentIndexVersion = index ? index.version : null;
  314. if ( storedIndexVersion !== currentIndexVersion ) {
  315. storedGeometryData.indexVersion = currentIndexVersion;
  316. return false;
  317. }
  318. // check drawRange
  319. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  320. storedGeometryData.drawRange.start = geometry.drawRange.start;
  321. storedGeometryData.drawRange.count = geometry.drawRange.count;
  322. return false;
  323. }
  324. // morph targets
  325. if ( renderObjectData.morphTargetInfluences ) {
  326. let morphChanged = false;
  327. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  328. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  329. morphChanged = true;
  330. }
  331. }
  332. if ( morphChanged ) return true;
  333. }
  334. // lights
  335. if ( renderObjectData.lights ) {
  336. for ( let i = 0; i < lightsData.length; i ++ ) {
  337. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  338. return false;
  339. }
  340. }
  341. }
  342. // center
  343. if ( renderObjectData.center ) {
  344. if ( renderObjectData.center.equals( object.center ) === false ) {
  345. renderObjectData.center.copy( object.center );
  346. return true;
  347. }
  348. }
  349. // bundle
  350. if ( renderObject.bundle !== null ) {
  351. renderObjectData.version = renderObject.bundle.version;
  352. }
  353. return true;
  354. }
  355. /**
  356. * Returns the lights data for the given material lights.
  357. *
  358. * @param {Array<Light>} materialLights - The material lights.
  359. * @return {Array<Object>} The lights data for the given material lights.
  360. */
  361. getLightsData( materialLights ) {
  362. const lights = [];
  363. for ( const light of materialLights ) {
  364. if ( light.isSpotLight === true && light.map !== null ) {
  365. // only add lights that have a map
  366. lights.push( { map: light.map.version } );
  367. }
  368. }
  369. return lights;
  370. }
  371. /**
  372. * Returns the lights for the given lights node and render ID.
  373. *
  374. * @param {LightsNode} lightsNode - The lights node.
  375. * @param {number} renderId - The render ID.
  376. * @return {Array} The lights for the given lights node and render ID.
  377. */
  378. getLights( lightsNode, renderId ) {
  379. if ( _lightsCache.has( lightsNode ) ) {
  380. const cached = _lightsCache.get( lightsNode );
  381. if ( cached.renderId === renderId ) {
  382. return cached.lightsData;
  383. }
  384. }
  385. const lightsData = this.getLightsData( lightsNode.getLights() );
  386. _lightsCache.set( lightsNode, { renderId, lightsData } );
  387. return lightsData;
  388. }
  389. /**
  390. * Checks if the given render object requires a refresh.
  391. *
  392. * @param {RenderObject} renderObject - The render object.
  393. * @param {NodeFrame} nodeFrame - The current node frame.
  394. * @return {boolean} Whether the given render object requires a refresh or not.
  395. */
  396. needsRefresh( renderObject, nodeFrame ) {
  397. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  398. return true;
  399. const { renderId } = nodeFrame;
  400. if ( this.renderId !== renderId ) {
  401. this.renderId = renderId;
  402. return true;
  403. }
  404. const isStatic = renderObject.object.static === true;
  405. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  406. if ( isStatic || isBundle )
  407. return false;
  408. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  409. const notEqual = this.equals( renderObject, lightsData ) !== true;
  410. return notEqual;
  411. }
  412. }
  413. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  414. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  415. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  416. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  417. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  418. function cyrb53( value, seed = 0 ) {
  419. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  420. if ( value instanceof Array ) {
  421. for ( let i = 0, val; i < value.length; i ++ ) {
  422. val = value[ i ];
  423. h1 = Math.imul( h1 ^ val, 2654435761 );
  424. h2 = Math.imul( h2 ^ val, 1597334677 );
  425. }
  426. } else {
  427. for ( let i = 0, ch; i < value.length; i ++ ) {
  428. ch = value.charCodeAt( i );
  429. h1 = Math.imul( h1 ^ ch, 2654435761 );
  430. h2 = Math.imul( h2 ^ ch, 1597334677 );
  431. }
  432. }
  433. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  434. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  435. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  436. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  437. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  438. }
  439. /**
  440. * Computes a hash for the given string.
  441. *
  442. * @method
  443. * @param {string} str - The string to be hashed.
  444. * @return {number} The hash.
  445. */
  446. const hashString = ( str ) => cyrb53( str );
  447. /**
  448. * Computes a hash for the given array.
  449. *
  450. * @method
  451. * @param {Array<number>} array - The array to be hashed.
  452. * @return {number} The hash.
  453. */
  454. const hashArray = ( array ) => cyrb53( array );
  455. /**
  456. * Computes a hash for the given list of parameters.
  457. *
  458. * @method
  459. * @param {...number} params - A list of parameters.
  460. * @return {number} The hash.
  461. */
  462. const hash$1 = ( ...params ) => cyrb53( params );
  463. /**
  464. * Computes a cache key for the given node.
  465. *
  466. * @method
  467. * @param {Object|Node} object - The object to be hashed.
  468. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  469. * @return {number} The hash.
  470. */
  471. function getCacheKey$1( object, force = false ) {
  472. const values = [];
  473. if ( object.isNode === true ) {
  474. values.push( object.id );
  475. object = object.getSelf();
  476. }
  477. for ( const { property, childNode } of getNodeChildren( object ) ) {
  478. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  479. }
  480. return cyrb53( values );
  481. }
  482. /**
  483. * This generator function can be used to iterate over the node children
  484. * of the given object.
  485. *
  486. * @generator
  487. * @param {Object} node - The object to be hashed.
  488. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  489. * @yields {Object} A result node holding the property, index (if available) and the child node.
  490. */
  491. function* getNodeChildren( node, toJSON = false ) {
  492. for ( const property in node ) {
  493. // Ignore private properties.
  494. if ( property.startsWith( '_' ) === true ) continue;
  495. const object = node[ property ];
  496. if ( Array.isArray( object ) === true ) {
  497. for ( let i = 0; i < object.length; i ++ ) {
  498. const child = object[ i ];
  499. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  500. yield { property, index: i, childNode: child };
  501. }
  502. }
  503. } else if ( object && object.isNode === true ) {
  504. yield { property, childNode: object };
  505. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  506. for ( const subProperty in object ) {
  507. // Ignore private properties.
  508. if ( subProperty.startsWith( '_' ) === true ) continue;
  509. const child = object[ subProperty ];
  510. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  511. yield { property, index: subProperty, childNode: child };
  512. }
  513. }
  514. }
  515. }
  516. }
  517. const typeFromLength = /*@__PURE__*/ new Map( [
  518. [ 1, 'float' ],
  519. [ 2, 'vec2' ],
  520. [ 3, 'vec3' ],
  521. [ 4, 'vec4' ],
  522. [ 9, 'mat3' ],
  523. [ 16, 'mat4' ]
  524. ] );
  525. const dataFromObject = /*@__PURE__*/ new WeakMap();
  526. /**
  527. * Returns the data type for the given the length.
  528. *
  529. * @method
  530. * @param {number} length - The length.
  531. * @return {string} The data type.
  532. */
  533. function getTypeFromLength( length ) {
  534. return typeFromLength.get( length );
  535. }
  536. /**
  537. * Returns the typed array for the given data type.
  538. *
  539. * @method
  540. * @param {string} type - The data type.
  541. * @return {TypedArray} The typed array.
  542. */
  543. function getTypedArrayFromType( type ) {
  544. // Handle component type for vectors and matrices
  545. if ( /[iu]?vec\d/.test( type ) ) {
  546. // Handle int vectors
  547. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  548. // Handle uint vectors
  549. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  550. // Default to float vectors
  551. return Float32Array;
  552. }
  553. // Handle matrices (always float)
  554. if ( /mat\d/.test( type ) ) return Float32Array;
  555. // Basic types
  556. if ( /float/.test( type ) ) return Float32Array;
  557. if ( /uint/.test( type ) ) return Uint32Array;
  558. if ( /int/.test( type ) ) return Int32Array;
  559. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  560. }
  561. /**
  562. * Returns the length for the given data type.
  563. *
  564. * @method
  565. * @param {string} type - The data type.
  566. * @return {number} The length.
  567. */
  568. function getLengthFromType( type ) {
  569. if ( /float|int|uint/.test( type ) ) return 1;
  570. if ( /vec2/.test( type ) ) return 2;
  571. if ( /vec3/.test( type ) ) return 3;
  572. if ( /vec4/.test( type ) ) return 4;
  573. if ( /mat2/.test( type ) ) return 4;
  574. if ( /mat3/.test( type ) ) return 9;
  575. if ( /mat4/.test( type ) ) return 16;
  576. console.error( 'THREE.TSL: Unsupported type:', type );
  577. }
  578. /**
  579. * Returns the gpu memory length for the given data type.
  580. *
  581. * @method
  582. * @param {string} type - The data type.
  583. * @return {number} The length.
  584. */
  585. function getMemoryLengthFromType( type ) {
  586. if ( /float|int|uint/.test( type ) ) return 1;
  587. if ( /vec2/.test( type ) ) return 2;
  588. if ( /vec3/.test( type ) ) return 3;
  589. if ( /vec4/.test( type ) ) return 4;
  590. if ( /mat2/.test( type ) ) return 4;
  591. if ( /mat3/.test( type ) ) return 12;
  592. if ( /mat4/.test( type ) ) return 16;
  593. console.error( 'THREE.TSL: Unsupported type:', type );
  594. }
  595. /**
  596. * Returns the byte boundary for the given data type.
  597. *
  598. * @method
  599. * @param {string} type - The data type.
  600. * @return {number} The byte boundary.
  601. */
  602. function getByteBoundaryFromType( type ) {
  603. if ( /float|int|uint/.test( type ) ) return 4;
  604. if ( /vec2/.test( type ) ) return 8;
  605. if ( /vec3/.test( type ) ) return 16;
  606. if ( /vec4/.test( type ) ) return 16;
  607. if ( /mat2/.test( type ) ) return 8;
  608. if ( /mat3/.test( type ) ) return 48;
  609. if ( /mat4/.test( type ) ) return 64;
  610. console.error( 'THREE.TSL: Unsupported type:', type );
  611. }
  612. /**
  613. * Returns the data type for the given value.
  614. *
  615. * @method
  616. * @param {any} value - The value.
  617. * @return {?string} The data type.
  618. */
  619. function getValueType( value ) {
  620. if ( value === undefined || value === null ) return null;
  621. const typeOf = typeof value;
  622. if ( value.isNode === true ) {
  623. return 'node';
  624. } else if ( typeOf === 'number' ) {
  625. return 'float';
  626. } else if ( typeOf === 'boolean' ) {
  627. return 'bool';
  628. } else if ( typeOf === 'string' ) {
  629. return 'string';
  630. } else if ( typeOf === 'function' ) {
  631. return 'shader';
  632. } else if ( value.isVector2 === true ) {
  633. return 'vec2';
  634. } else if ( value.isVector3 === true ) {
  635. return 'vec3';
  636. } else if ( value.isVector4 === true ) {
  637. return 'vec4';
  638. } else if ( value.isMatrix2 === true ) {
  639. return 'mat2';
  640. } else if ( value.isMatrix3 === true ) {
  641. return 'mat3';
  642. } else if ( value.isMatrix4 === true ) {
  643. return 'mat4';
  644. } else if ( value.isColor === true ) {
  645. return 'color';
  646. } else if ( value instanceof ArrayBuffer ) {
  647. return 'ArrayBuffer';
  648. }
  649. return null;
  650. }
  651. /**
  652. * Returns the value/object for the given data type and parameters.
  653. *
  654. * @method
  655. * @param {string} type - The given type.
  656. * @param {...any} params - A parameter list.
  657. * @return {any} The value/object.
  658. */
  659. function getValueFromType( type, ...params ) {
  660. const last4 = type ? type.slice( -4 ) : undefined;
  661. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  662. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  663. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  664. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  665. }
  666. if ( type === 'color' ) {
  667. return new Color( ...params );
  668. } else if ( last4 === 'vec2' ) {
  669. return new Vector2( ...params );
  670. } else if ( last4 === 'vec3' ) {
  671. return new Vector3( ...params );
  672. } else if ( last4 === 'vec4' ) {
  673. return new Vector4( ...params );
  674. } else if ( last4 === 'mat2' ) {
  675. return new Matrix2( ...params );
  676. } else if ( last4 === 'mat3' ) {
  677. return new Matrix3( ...params );
  678. } else if ( last4 === 'mat4' ) {
  679. return new Matrix4( ...params );
  680. } else if ( type === 'bool' ) {
  681. return params[ 0 ] || false;
  682. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  683. return params[ 0 ] || 0;
  684. } else if ( type === 'string' ) {
  685. return params[ 0 ] || '';
  686. } else if ( type === 'ArrayBuffer' ) {
  687. return base64ToArrayBuffer( params[ 0 ] );
  688. }
  689. return null;
  690. }
  691. /**
  692. * Gets the object data that can be shared between different rendering steps.
  693. *
  694. * @param {Object} object - The object to get the data for.
  695. * @return {Object} The object data.
  696. */
  697. function getDataFromObject( object ) {
  698. let data = dataFromObject.get( object );
  699. if ( data === undefined ) {
  700. data = {};
  701. dataFromObject.set( object, data );
  702. }
  703. return data;
  704. }
  705. /**
  706. * Converts the given array buffer to a Base64 string.
  707. *
  708. * @method
  709. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  710. * @return {string} The Base64 string.
  711. */
  712. function arrayBufferToBase64( arrayBuffer ) {
  713. let chars = '';
  714. const array = new Uint8Array( arrayBuffer );
  715. for ( let i = 0; i < array.length; i ++ ) {
  716. chars += String.fromCharCode( array[ i ] );
  717. }
  718. return btoa( chars );
  719. }
  720. /**
  721. * Converts the given Base64 string to an array buffer.
  722. *
  723. * @method
  724. * @param {string} base64 - The Base64 string.
  725. * @return {ArrayBuffer} The array buffer.
  726. */
  727. function base64ToArrayBuffer( base64 ) {
  728. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  729. }
  730. var NodeUtils = /*#__PURE__*/Object.freeze({
  731. __proto__: null,
  732. arrayBufferToBase64: arrayBufferToBase64,
  733. base64ToArrayBuffer: base64ToArrayBuffer,
  734. getByteBoundaryFromType: getByteBoundaryFromType,
  735. getCacheKey: getCacheKey$1,
  736. getDataFromObject: getDataFromObject,
  737. getLengthFromType: getLengthFromType,
  738. getMemoryLengthFromType: getMemoryLengthFromType,
  739. getNodeChildren: getNodeChildren,
  740. getTypeFromLength: getTypeFromLength,
  741. getTypedArrayFromType: getTypedArrayFromType,
  742. getValueFromType: getValueFromType,
  743. getValueType: getValueType,
  744. hash: hash$1,
  745. hashArray: hashArray,
  746. hashString: hashString
  747. });
  748. /**
  749. * Possible shader stages.
  750. *
  751. * @property {string} VERTEX The vertex shader stage.
  752. * @property {string} FRAGMENT The fragment shader stage.
  753. */
  754. const NodeShaderStage = {
  755. VERTEX: 'vertex',
  756. FRAGMENT: 'fragment'
  757. };
  758. /**
  759. * Update types of a node.
  760. *
  761. * @property {string} NONE The update method is not executed.
  762. * @property {string} FRAME The update method is executed per frame.
  763. * @property {string} RENDER The update method is executed per render. A frame might be produced by multiple render calls so this value allows more detailed updates than FRAME.
  764. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  765. */
  766. const NodeUpdateType = {
  767. NONE: 'none',
  768. FRAME: 'frame',
  769. RENDER: 'render',
  770. OBJECT: 'object'
  771. };
  772. /**
  773. * Data types of a node.
  774. *
  775. * @property {string} BOOLEAN Boolean type.
  776. * @property {string} INTEGER Integer type.
  777. * @property {string} FLOAT Float type.
  778. * @property {string} VECTOR2 Two-dimensional vector type.
  779. * @property {string} VECTOR3 Three-dimensional vector type.
  780. * @property {string} VECTOR4 Four-dimensional vector type.
  781. * @property {string} MATRIX2 2x2 matrix type.
  782. * @property {string} MATRIX3 3x3 matrix type.
  783. * @property {string} MATRIX4 4x4 matrix type.
  784. */
  785. const NodeType = {
  786. BOOLEAN: 'bool',
  787. INTEGER: 'int',
  788. FLOAT: 'float',
  789. VECTOR2: 'vec2',
  790. VECTOR3: 'vec3',
  791. VECTOR4: 'vec4',
  792. MATRIX2: 'mat2',
  793. MATRIX3: 'mat3',
  794. MATRIX4: 'mat4'
  795. };
  796. /**
  797. * Access types of a node. These are relevant for compute and storage usage.
  798. *
  799. * @property {string} READ_ONLY Read-only access
  800. * @property {string} WRITE_ONLY Write-only access.
  801. * @property {string} READ_WRITE Read and write access.
  802. */
  803. const NodeAccess = {
  804. READ_ONLY: 'readOnly',
  805. WRITE_ONLY: 'writeOnly',
  806. READ_WRITE: 'readWrite',
  807. };
  808. const defaultShaderStages = [ 'fragment', 'vertex' ];
  809. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  810. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  811. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  812. const _parentBuildStage = {
  813. analyze: 'setup',
  814. generate: 'analyze'
  815. };
  816. let _nodeId = 0;
  817. /**
  818. * Base class for all nodes.
  819. *
  820. * @augments EventDispatcher
  821. */
  822. class Node extends EventDispatcher {
  823. static get type() {
  824. return 'Node';
  825. }
  826. /**
  827. * Constructs a new node.
  828. *
  829. * @param {?string} nodeType - The node type.
  830. */
  831. constructor( nodeType = null ) {
  832. super();
  833. /**
  834. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  835. *
  836. * @type {?string}
  837. * @default null
  838. */
  839. this.nodeType = nodeType;
  840. /**
  841. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  842. *
  843. * @type {string}
  844. * @default 'none'
  845. */
  846. this.updateType = NodeUpdateType.NONE;
  847. /**
  848. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  849. *
  850. * @type {string}
  851. * @default 'none'
  852. */
  853. this.updateBeforeType = NodeUpdateType.NONE;
  854. /**
  855. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  856. *
  857. * @type {string}
  858. * @default 'none'
  859. */
  860. this.updateAfterType = NodeUpdateType.NONE;
  861. /**
  862. * The UUID of the node.
  863. *
  864. * @type {string}
  865. * @readonly
  866. */
  867. this.uuid = MathUtils.generateUUID();
  868. /**
  869. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  870. *
  871. * @type {number}
  872. * @readonly
  873. * @default 0
  874. */
  875. this.version = 0;
  876. /**
  877. * Whether this node is global or not. This property is relevant for the internal
  878. * node caching system. All nodes which should be declared just once should
  879. * set this flag to `true` (a typical example is {@link AttributeNode}).
  880. *
  881. * @type {boolean}
  882. * @default false
  883. */
  884. this.global = false;
  885. /**
  886. * Create a list of parents for this node during the build process.
  887. *
  888. * @type {boolean}
  889. * @default false
  890. */
  891. this.parents = false;
  892. /**
  893. * This flag can be used for type testing.
  894. *
  895. * @type {boolean}
  896. * @readonly
  897. * @default true
  898. */
  899. this.isNode = true;
  900. // private
  901. /**
  902. * The cache key of this node.
  903. *
  904. * @private
  905. * @type {?number}
  906. * @default null
  907. */
  908. this._cacheKey = null;
  909. /**
  910. * The cache key 's version.
  911. *
  912. * @private
  913. * @type {number}
  914. * @default 0
  915. */
  916. this._cacheKeyVersion = 0;
  917. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  918. }
  919. /**
  920. * Set this property to `true` when the node should be regenerated.
  921. *
  922. * @type {boolean}
  923. * @default false
  924. * @param {boolean} value
  925. */
  926. set needsUpdate( value ) {
  927. if ( value === true ) {
  928. this.version ++;
  929. }
  930. }
  931. /**
  932. * The type of the class. The value is usually the constructor name.
  933. *
  934. * @type {string}
  935. * @readonly
  936. */
  937. get type() {
  938. return this.constructor.type;
  939. }
  940. /**
  941. * Convenient method for defining {@link Node#update}.
  942. *
  943. * @param {Function} callback - The update method.
  944. * @param {string} updateType - The update type.
  945. * @return {Node} A reference to this node.
  946. */
  947. onUpdate( callback, updateType ) {
  948. this.updateType = updateType;
  949. this.update = callback.bind( this.getSelf() );
  950. return this;
  951. }
  952. /**
  953. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  954. * this method automatically sets the update type to `FRAME`.
  955. *
  956. * @param {Function} callback - The update method.
  957. * @return {Node} A reference to this node.
  958. */
  959. onFrameUpdate( callback ) {
  960. return this.onUpdate( callback, NodeUpdateType.FRAME );
  961. }
  962. /**
  963. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  964. * this method automatically sets the update type to `RENDER`.
  965. *
  966. * @param {Function} callback - The update method.
  967. * @return {Node} A reference to this node.
  968. */
  969. onRenderUpdate( callback ) {
  970. return this.onUpdate( callback, NodeUpdateType.RENDER );
  971. }
  972. /**
  973. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  974. * this method automatically sets the update type to `OBJECT`.
  975. *
  976. * @param {Function} callback - The update method.
  977. * @return {Node} A reference to this node.
  978. */
  979. onObjectUpdate( callback ) {
  980. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  981. }
  982. /**
  983. * Convenient method for defining {@link Node#updateReference}.
  984. *
  985. * @param {Function} callback - The update method.
  986. * @return {Node} A reference to this node.
  987. */
  988. onReference( callback ) {
  989. this.updateReference = callback.bind( this.getSelf() );
  990. return this;
  991. }
  992. /**
  993. * The `this` reference might point to a Proxy so this method can be used
  994. * to get the reference to the actual node instance.
  995. *
  996. * @return {Node} A reference to the node.
  997. */
  998. getSelf() {
  999. // Returns non-node object.
  1000. return this.self || this;
  1001. }
  1002. /**
  1003. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1004. * to such objects based on a given state (e.g. the current node frame or builder).
  1005. *
  1006. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1007. * @return {any} The updated reference.
  1008. */
  1009. updateReference( /*state*/ ) {
  1010. return this;
  1011. }
  1012. /**
  1013. * By default this method returns the value of the {@link Node#global} flag. This method
  1014. * can be overwritten in derived classes if an analytical way is required to determine the
  1015. * global cache referring to the current shader-stage.
  1016. *
  1017. * @param {NodeBuilder} builder - The current node builder.
  1018. * @return {boolean} Whether this node is global or not.
  1019. */
  1020. isGlobal( /*builder*/ ) {
  1021. return this.global;
  1022. }
  1023. /**
  1024. * Generator function that can be used to iterate over the child nodes.
  1025. *
  1026. * @generator
  1027. * @yields {Node} A child node.
  1028. */
  1029. * getChildren() {
  1030. for ( const { childNode } of getNodeChildren( this ) ) {
  1031. yield childNode;
  1032. }
  1033. }
  1034. /**
  1035. * Calling this method dispatches the `dispose` event. This event can be used
  1036. * to register event listeners for clean up tasks.
  1037. */
  1038. dispose() {
  1039. this.dispatchEvent( { type: 'dispose' } );
  1040. }
  1041. /**
  1042. * Callback for {@link Node#traverse}.
  1043. *
  1044. * @callback traverseCallback
  1045. * @param {Node} node - The current node.
  1046. */
  1047. /**
  1048. * Can be used to traverse through the node's hierarchy.
  1049. *
  1050. * @param {traverseCallback} callback - A callback that is executed per node.
  1051. */
  1052. traverse( callback ) {
  1053. callback( this );
  1054. for ( const childNode of this.getChildren() ) {
  1055. childNode.traverse( callback );
  1056. }
  1057. }
  1058. /**
  1059. * Returns the cache key for this node.
  1060. *
  1061. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1062. * @return {number} The cache key of the node.
  1063. */
  1064. getCacheKey( force = false ) {
  1065. force = force || this.version !== this._cacheKeyVersion;
  1066. if ( force === true || this._cacheKey === null ) {
  1067. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1068. this._cacheKeyVersion = this.version;
  1069. }
  1070. return this._cacheKey;
  1071. }
  1072. /**
  1073. * Generate a custom cache key for this node.
  1074. *
  1075. * @return {number} The cache key of the node.
  1076. */
  1077. customCacheKey() {
  1078. return 0;
  1079. }
  1080. /**
  1081. * Returns the references to this node which is by default `this`.
  1082. *
  1083. * @return {Node} A reference to this node.
  1084. */
  1085. getScope() {
  1086. return this;
  1087. }
  1088. /**
  1089. * Returns the hash of the node which is used to identify the node. By default it's
  1090. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1091. * depending on their implementation.
  1092. *
  1093. * @param {NodeBuilder} builder - The current node builder.
  1094. * @return {string} The hash.
  1095. */
  1096. getHash( /*builder*/ ) {
  1097. return this.uuid;
  1098. }
  1099. /**
  1100. * Returns the update type of {@link Node#update}.
  1101. *
  1102. * @return {NodeUpdateType} The update type.
  1103. */
  1104. getUpdateType() {
  1105. return this.updateType;
  1106. }
  1107. /**
  1108. * Returns the update type of {@link Node#updateBefore}.
  1109. *
  1110. * @return {NodeUpdateType} The update type.
  1111. */
  1112. getUpdateBeforeType() {
  1113. return this.updateBeforeType;
  1114. }
  1115. /**
  1116. * Returns the update type of {@link Node#updateAfter}.
  1117. *
  1118. * @return {NodeUpdateType} The update type.
  1119. */
  1120. getUpdateAfterType() {
  1121. return this.updateAfterType;
  1122. }
  1123. /**
  1124. * Certain types are composed of multiple elements. For example a `vec3`
  1125. * is composed of three `float` values. This method returns the type of
  1126. * these elements.
  1127. *
  1128. * @param {NodeBuilder} builder - The current node builder.
  1129. * @return {string} The type of the node.
  1130. */
  1131. getElementType( builder ) {
  1132. const type = this.getNodeType( builder );
  1133. const elementType = builder.getElementType( type );
  1134. return elementType;
  1135. }
  1136. /**
  1137. * Returns the node member type for the given name.
  1138. *
  1139. * @param {NodeBuilder} builder - The current node builder.
  1140. * @param {string} name - The name of the member.
  1141. * @return {string} The type of the node.
  1142. */
  1143. getMemberType( /*builder, name*/ ) {
  1144. return 'void';
  1145. }
  1146. /**
  1147. * Returns the node's type.
  1148. *
  1149. * @param {NodeBuilder} builder - The current node builder.
  1150. * @return {string} The type of the node.
  1151. */
  1152. getNodeType( builder ) {
  1153. const nodeProperties = builder.getNodeProperties( this );
  1154. if ( nodeProperties.outputNode ) {
  1155. return nodeProperties.outputNode.getNodeType( builder );
  1156. }
  1157. return this.nodeType;
  1158. }
  1159. /**
  1160. * This method is used during the build process of a node and ensures
  1161. * equal nodes are not built multiple times but just once. For example if
  1162. * `attribute( 'uv' )` is used multiple times by the user, the build
  1163. * process makes sure to process just the first node.
  1164. *
  1165. * @param {NodeBuilder} builder - The current node builder.
  1166. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1167. */
  1168. getShared( builder ) {
  1169. const hash = this.getHash( builder );
  1170. const nodeFromHash = builder.getNodeFromHash( hash );
  1171. return nodeFromHash || this;
  1172. }
  1173. /**
  1174. * Returns the number of elements in the node array.
  1175. *
  1176. * @param {NodeBuilder} builder - The current node builder.
  1177. * @return {?number} The number of elements in the node array.
  1178. */
  1179. getArrayCount( /*builder*/ ) {
  1180. return null;
  1181. }
  1182. /**
  1183. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1184. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1185. * The output node must be returned in the `return` statement.
  1186. *
  1187. * @param {NodeBuilder} builder - The current node builder.
  1188. * @return {?Node} The output node.
  1189. */
  1190. setup( builder ) {
  1191. const nodeProperties = builder.getNodeProperties( this );
  1192. let index = 0;
  1193. for ( const childNode of this.getChildren() ) {
  1194. nodeProperties[ 'node' + index ++ ] = childNode;
  1195. }
  1196. // return a outputNode if exists or null
  1197. return nodeProperties.outputNode || null;
  1198. }
  1199. /**
  1200. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1201. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1202. *
  1203. * @param {NodeBuilder} builder - The current node builder.
  1204. * @param {?Node} output - The target output node.
  1205. */
  1206. analyze( builder, output = null ) {
  1207. const usageCount = builder.increaseUsage( this );
  1208. if ( this.parents === true ) {
  1209. const nodeData = builder.getDataFromNode( this, 'any' );
  1210. nodeData.stages = nodeData.stages || {};
  1211. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1212. nodeData.stages[ builder.shaderStage ].push( output );
  1213. }
  1214. if ( usageCount === 1 ) {
  1215. // node flow children
  1216. const nodeProperties = builder.getNodeProperties( this );
  1217. for ( const childNode of Object.values( nodeProperties ) ) {
  1218. if ( childNode && childNode.isNode === true ) {
  1219. childNode.build( builder, this );
  1220. }
  1221. }
  1222. }
  1223. }
  1224. /**
  1225. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1226. * This state builds the output node and returns the resulting shader string.
  1227. *
  1228. * @param {NodeBuilder} builder - The current node builder.
  1229. * @param {?string} output - Can be used to define the output type.
  1230. * @return {?string} The generated shader string.
  1231. */
  1232. generate( builder, output ) {
  1233. const { outputNode } = builder.getNodeProperties( this );
  1234. if ( outputNode && outputNode.isNode === true ) {
  1235. return outputNode.build( builder, output );
  1236. }
  1237. }
  1238. /**
  1239. * The method can be implemented to update the node's internal state before it is used to render an object.
  1240. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1241. *
  1242. * @abstract
  1243. * @param {NodeFrame} frame - A reference to the current node frame.
  1244. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1245. */
  1246. updateBefore( /*frame*/ ) {
  1247. console.warn( 'Abstract function.' );
  1248. }
  1249. /**
  1250. * The method can be implemented to update the node's internal state after it was used to render an object.
  1251. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1252. *
  1253. * @abstract
  1254. * @param {NodeFrame} frame - A reference to the current node frame.
  1255. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1256. */
  1257. updateAfter( /*frame*/ ) {
  1258. console.warn( 'Abstract function.' );
  1259. }
  1260. /**
  1261. * The method can be implemented to update the node's internal state when it is used to render an object.
  1262. * The {@link Node#updateType} property defines how often the update is executed.
  1263. *
  1264. * @abstract
  1265. * @param {NodeFrame} frame - A reference to the current node frame.
  1266. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1267. */
  1268. update( /*frame*/ ) {
  1269. console.warn( 'Abstract function.' );
  1270. }
  1271. /**
  1272. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1273. * - **setup**: Prepares the node and its children for the build process. This process can also create new nodes. Returns the node itself or a variant.
  1274. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1275. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1276. *
  1277. * @param {NodeBuilder} builder - The current node builder.
  1278. * @param {string|Node|null} [output=null] - Can be used to define the output type.
  1279. * @return {Node|string|null} The result of the build process, depending on the build stage.
  1280. */
  1281. build( builder, output = null ) {
  1282. const refNode = this.getShared( builder );
  1283. if ( this !== refNode ) {
  1284. return refNode.build( builder, output );
  1285. }
  1286. //
  1287. const nodeData = builder.getDataFromNode( this );
  1288. nodeData.buildStages = nodeData.buildStages || {};
  1289. nodeData.buildStages[ builder.buildStage ] = true;
  1290. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1291. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1292. // force parent build stage (setup or analyze)
  1293. const previousBuildStage = builder.getBuildStage();
  1294. builder.setBuildStage( parentBuildStage );
  1295. this.build( builder );
  1296. builder.setBuildStage( previousBuildStage );
  1297. }
  1298. //
  1299. builder.addNode( this );
  1300. builder.addChain( this );
  1301. /* Build stages expected results:
  1302. - "setup" -> Node
  1303. - "analyze" -> null
  1304. - "generate" -> String
  1305. */
  1306. let result = null;
  1307. const buildStage = builder.getBuildStage();
  1308. if ( buildStage === 'setup' ) {
  1309. this.updateReference( builder );
  1310. const properties = builder.getNodeProperties( this );
  1311. if ( properties.initialized !== true ) {
  1312. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1313. properties.initialized = true;
  1314. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1315. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1316. // !! no outputNode !!
  1317. //outputNode = builder.stack;
  1318. }*/
  1319. for ( const childNode of Object.values( properties ) ) {
  1320. if ( childNode && childNode.isNode === true ) {
  1321. if ( childNode.parents === true ) {
  1322. const childProperties = builder.getNodeProperties( childNode );
  1323. childProperties.parents = childProperties.parents || [];
  1324. childProperties.parents.push( this );
  1325. }
  1326. childNode.build( builder );
  1327. }
  1328. }
  1329. }
  1330. result = properties.outputNode;
  1331. } else if ( buildStage === 'analyze' ) {
  1332. this.analyze( builder, output );
  1333. } else if ( buildStage === 'generate' ) {
  1334. const isGenerateOnce = this.generate.length === 1;
  1335. if ( isGenerateOnce ) {
  1336. const type = this.getNodeType( builder );
  1337. const nodeData = builder.getDataFromNode( this );
  1338. result = nodeData.snippet;
  1339. if ( result === undefined ) {
  1340. if ( nodeData.generated === undefined ) {
  1341. nodeData.generated = true;
  1342. result = this.generate( builder ) || '';
  1343. nodeData.snippet = result;
  1344. } else {
  1345. console.warn( 'THREE.Node: Recursion detected.', this );
  1346. result = '/* Recursion detected. */';
  1347. }
  1348. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1349. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1350. }
  1351. result = builder.format( result, type, output );
  1352. } else {
  1353. result = this.generate( builder, output ) || '';
  1354. }
  1355. }
  1356. builder.removeChain( this );
  1357. builder.addSequentialNode( this );
  1358. return result;
  1359. }
  1360. /**
  1361. * Returns the child nodes as a JSON object.
  1362. *
  1363. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1364. */
  1365. getSerializeChildren() {
  1366. return getNodeChildren( this );
  1367. }
  1368. /**
  1369. * Serializes the node to JSON.
  1370. *
  1371. * @param {Object} json - The output JSON object.
  1372. */
  1373. serialize( json ) {
  1374. const nodeChildren = this.getSerializeChildren();
  1375. const inputNodes = {};
  1376. for ( const { property, index, childNode } of nodeChildren ) {
  1377. if ( index !== undefined ) {
  1378. if ( inputNodes[ property ] === undefined ) {
  1379. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1380. }
  1381. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1382. } else {
  1383. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1384. }
  1385. }
  1386. if ( Object.keys( inputNodes ).length > 0 ) {
  1387. json.inputNodes = inputNodes;
  1388. }
  1389. }
  1390. /**
  1391. * Deserializes the node from the given JSON.
  1392. *
  1393. * @param {Object} json - The JSON object.
  1394. */
  1395. deserialize( json ) {
  1396. if ( json.inputNodes !== undefined ) {
  1397. const nodes = json.meta.nodes;
  1398. for ( const property in json.inputNodes ) {
  1399. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1400. const inputArray = [];
  1401. for ( const uuid of json.inputNodes[ property ] ) {
  1402. inputArray.push( nodes[ uuid ] );
  1403. }
  1404. this[ property ] = inputArray;
  1405. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1406. const inputObject = {};
  1407. for ( const subProperty in json.inputNodes[ property ] ) {
  1408. const uuid = json.inputNodes[ property ][ subProperty ];
  1409. inputObject[ subProperty ] = nodes[ uuid ];
  1410. }
  1411. this[ property ] = inputObject;
  1412. } else {
  1413. const uuid = json.inputNodes[ property ];
  1414. this[ property ] = nodes[ uuid ];
  1415. }
  1416. }
  1417. }
  1418. }
  1419. /**
  1420. * Serializes the node into the three.js JSON Object/Scene format.
  1421. *
  1422. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1423. * @return {Object} The serialized node.
  1424. */
  1425. toJSON( meta ) {
  1426. const { uuid, type } = this;
  1427. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1428. if ( isRoot ) {
  1429. meta = {
  1430. textures: {},
  1431. images: {},
  1432. nodes: {}
  1433. };
  1434. }
  1435. // serialize
  1436. let data = meta.nodes[ uuid ];
  1437. if ( data === undefined ) {
  1438. data = {
  1439. uuid,
  1440. type,
  1441. meta,
  1442. metadata: {
  1443. version: 4.7,
  1444. type: 'Node',
  1445. generator: 'Node.toJSON'
  1446. }
  1447. };
  1448. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1449. this.serialize( data );
  1450. delete data.meta;
  1451. }
  1452. // TODO: Copied from Object3D.toJSON
  1453. function extractFromCache( cache ) {
  1454. const values = [];
  1455. for ( const key in cache ) {
  1456. const data = cache[ key ];
  1457. delete data.metadata;
  1458. values.push( data );
  1459. }
  1460. return values;
  1461. }
  1462. if ( isRoot ) {
  1463. const textures = extractFromCache( meta.textures );
  1464. const images = extractFromCache( meta.images );
  1465. const nodes = extractFromCache( meta.nodes );
  1466. if ( textures.length > 0 ) data.textures = textures;
  1467. if ( images.length > 0 ) data.images = images;
  1468. if ( nodes.length > 0 ) data.nodes = nodes;
  1469. }
  1470. return data;
  1471. }
  1472. }
  1473. /**
  1474. * Base class for representing element access on an array-like
  1475. * node data structures.
  1476. *
  1477. * @augments Node
  1478. */
  1479. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1480. static get type() {
  1481. return 'ArrayElementNode';
  1482. }
  1483. /**
  1484. * Constructs an array element node.
  1485. *
  1486. * @param {Node} node - The array-like node.
  1487. * @param {Node} indexNode - The index node that defines the element access.
  1488. */
  1489. constructor( node, indexNode ) {
  1490. super();
  1491. /**
  1492. * The array-like node.
  1493. *
  1494. * @type {Node}
  1495. */
  1496. this.node = node;
  1497. /**
  1498. * The index node that defines the element access.
  1499. *
  1500. * @type {Node}
  1501. */
  1502. this.indexNode = indexNode;
  1503. /**
  1504. * This flag can be used for type testing.
  1505. *
  1506. * @type {boolean}
  1507. * @readonly
  1508. * @default true
  1509. */
  1510. this.isArrayElementNode = true;
  1511. }
  1512. /**
  1513. * This method is overwritten since the node type is inferred from the array-like node.
  1514. *
  1515. * @param {NodeBuilder} builder - The current node builder.
  1516. * @return {string} The node type.
  1517. */
  1518. getNodeType( builder ) {
  1519. return this.node.getElementType( builder );
  1520. }
  1521. generate( builder ) {
  1522. const indexType = this.indexNode.getNodeType( builder );
  1523. const nodeSnippet = this.node.build( builder );
  1524. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1525. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1526. }
  1527. }
  1528. /**
  1529. * This module is part of the TSL core and usually not used in app level code.
  1530. * It represents a convert operation during the shader generation process
  1531. * meaning it converts the data type of a node to a target data type.
  1532. *
  1533. * @augments Node
  1534. */
  1535. class ConvertNode extends Node {
  1536. static get type() {
  1537. return 'ConvertNode';
  1538. }
  1539. /**
  1540. * Constructs a new convert node.
  1541. *
  1542. * @param {Node} node - The node which type should be converted.
  1543. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1544. */
  1545. constructor( node, convertTo ) {
  1546. super();
  1547. /**
  1548. * The node which type should be converted.
  1549. *
  1550. * @type {Node}
  1551. */
  1552. this.node = node;
  1553. /**
  1554. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1555. *
  1556. * @type {string}
  1557. */
  1558. this.convertTo = convertTo;
  1559. }
  1560. /**
  1561. * This method is overwritten since the implementation tries to infer the best
  1562. * matching type from the {@link ConvertNode#convertTo} property.
  1563. *
  1564. * @param {NodeBuilder} builder - The current node builder.
  1565. * @return {string} The node type.
  1566. */
  1567. getNodeType( builder ) {
  1568. const requestType = this.node.getNodeType( builder );
  1569. let convertTo = null;
  1570. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1571. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1572. convertTo = overloadingType;
  1573. }
  1574. }
  1575. return convertTo;
  1576. }
  1577. serialize( data ) {
  1578. super.serialize( data );
  1579. data.convertTo = this.convertTo;
  1580. }
  1581. deserialize( data ) {
  1582. super.deserialize( data );
  1583. this.convertTo = data.convertTo;
  1584. }
  1585. generate( builder, output ) {
  1586. const node = this.node;
  1587. const type = this.getNodeType( builder );
  1588. const snippet = node.build( builder, type );
  1589. return builder.format( snippet, type, output );
  1590. }
  1591. }
  1592. /**
  1593. * This module uses cache management to create temporary variables
  1594. * if the node is used more than once to prevent duplicate calculations.
  1595. *
  1596. * The class acts as a base class for many other nodes types.
  1597. *
  1598. * @augments Node
  1599. */
  1600. class TempNode extends Node {
  1601. static get type() {
  1602. return 'TempNode';
  1603. }
  1604. /**
  1605. * Constructs a temp node.
  1606. *
  1607. * @param {?string} nodeType - The node type.
  1608. */
  1609. constructor( nodeType = null ) {
  1610. super( nodeType );
  1611. /**
  1612. * This flag can be used for type testing.
  1613. *
  1614. * @type {boolean}
  1615. * @readonly
  1616. * @default true
  1617. */
  1618. this.isTempNode = true;
  1619. }
  1620. /**
  1621. * Whether this node is used more than once in context of other nodes.
  1622. *
  1623. * @param {NodeBuilder} builder - The node builder.
  1624. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1625. */
  1626. hasDependencies( builder ) {
  1627. return builder.getDataFromNode( this ).usageCount > 1;
  1628. }
  1629. build( builder, output ) {
  1630. const buildStage = builder.getBuildStage();
  1631. if ( buildStage === 'generate' ) {
  1632. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1633. const nodeData = builder.getDataFromNode( this );
  1634. if ( nodeData.propertyName !== undefined ) {
  1635. return builder.format( nodeData.propertyName, type, output );
  1636. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1637. const snippet = super.build( builder, type );
  1638. const nodeVar = builder.getVarFromNode( this, null, type );
  1639. const propertyName = builder.getPropertyName( nodeVar );
  1640. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1641. nodeData.snippet = snippet;
  1642. nodeData.propertyName = propertyName;
  1643. return builder.format( nodeData.propertyName, type, output );
  1644. }
  1645. }
  1646. return super.build( builder, output );
  1647. }
  1648. }
  1649. /**
  1650. * This module is part of the TSL core and usually not used in app level code.
  1651. * It represents a join operation during the shader generation process.
  1652. * For example in can compose/join two single floats into a `vec2` type.
  1653. *
  1654. * @augments TempNode
  1655. */
  1656. class JoinNode extends TempNode {
  1657. static get type() {
  1658. return 'JoinNode';
  1659. }
  1660. /**
  1661. * Constructs a new join node.
  1662. *
  1663. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1664. * @param {?string} [nodeType=null] - The node type.
  1665. */
  1666. constructor( nodes = [], nodeType = null ) {
  1667. super( nodeType );
  1668. /**
  1669. * An array of nodes that should be joined.
  1670. *
  1671. * @type {Array<Node>}
  1672. */
  1673. this.nodes = nodes;
  1674. }
  1675. /**
  1676. * This method is overwritten since the node type must be inferred from the
  1677. * joined data length if not explicitly defined.
  1678. *
  1679. * @param {NodeBuilder} builder - The current node builder.
  1680. * @return {string} The node type.
  1681. */
  1682. getNodeType( builder ) {
  1683. if ( this.nodeType !== null ) {
  1684. return builder.getVectorType( this.nodeType );
  1685. }
  1686. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1687. }
  1688. generate( builder, output ) {
  1689. const type = this.getNodeType( builder );
  1690. const maxLength = builder.getTypeLength( type );
  1691. const nodes = this.nodes;
  1692. const primitiveType = builder.getComponentType( type );
  1693. const snippetValues = [];
  1694. let length = 0;
  1695. for ( const input of nodes ) {
  1696. if ( length >= maxLength ) {
  1697. console.error( `THREE.TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1698. break;
  1699. }
  1700. let inputType = input.getNodeType( builder );
  1701. let inputTypeLength = builder.getTypeLength( inputType );
  1702. let inputSnippet;
  1703. if ( length + inputTypeLength > maxLength ) {
  1704. console.error( `THREE.TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1705. inputTypeLength = maxLength - length;
  1706. inputType = builder.getTypeFromLength( inputTypeLength );
  1707. }
  1708. length += inputTypeLength;
  1709. inputSnippet = input.build( builder, inputType );
  1710. const inputPrimitiveType = builder.getComponentType( inputType );
  1711. if ( inputPrimitiveType !== primitiveType ) {
  1712. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1713. }
  1714. snippetValues.push( inputSnippet );
  1715. }
  1716. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1717. return builder.format( snippet, type, output );
  1718. }
  1719. }
  1720. const _stringVectorComponents = vectorComponents.join( '' );
  1721. /**
  1722. * This module is part of the TSL core and usually not used in app level code.
  1723. * `SplitNode` represents a property access operation which means it is
  1724. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1725. * For example:
  1726. * ```js
  1727. * const redValue = color.r;
  1728. * ```
  1729. *
  1730. * @augments Node
  1731. */
  1732. class SplitNode extends Node {
  1733. static get type() {
  1734. return 'SplitNode';
  1735. }
  1736. /**
  1737. * Constructs a new split node.
  1738. *
  1739. * @param {Node} node - The node that should be accessed.
  1740. * @param {string} [components='x'] - The components that should be accessed.
  1741. */
  1742. constructor( node, components = 'x' ) {
  1743. super();
  1744. /**
  1745. * The node that should be accessed.
  1746. *
  1747. * @type {Node}
  1748. */
  1749. this.node = node;
  1750. /**
  1751. * The components that should be accessed.
  1752. *
  1753. * @type {string}
  1754. */
  1755. this.components = components;
  1756. /**
  1757. * This flag can be used for type testing.
  1758. *
  1759. * @type {boolean}
  1760. * @readonly
  1761. * @default true
  1762. */
  1763. this.isSplitNode = true;
  1764. }
  1765. /**
  1766. * Returns the vector length which is computed based on the requested components.
  1767. *
  1768. * @return {number} The vector length.
  1769. */
  1770. getVectorLength() {
  1771. let vectorLength = this.components.length;
  1772. for ( const c of this.components ) {
  1773. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1774. }
  1775. return vectorLength;
  1776. }
  1777. /**
  1778. * Returns the component type of the node's type.
  1779. *
  1780. * @param {NodeBuilder} builder - The current node builder.
  1781. * @return {string} The component type.
  1782. */
  1783. getComponentType( builder ) {
  1784. return builder.getComponentType( this.node.getNodeType( builder ) );
  1785. }
  1786. /**
  1787. * This method is overwritten since the node type is inferred from requested components.
  1788. *
  1789. * @param {NodeBuilder} builder - The current node builder.
  1790. * @return {string} The node type.
  1791. */
  1792. getNodeType( builder ) {
  1793. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1794. }
  1795. generate( builder, output ) {
  1796. const node = this.node;
  1797. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1798. let snippet = null;
  1799. if ( nodeTypeLength > 1 ) {
  1800. let type = null;
  1801. const componentsLength = this.getVectorLength();
  1802. if ( componentsLength >= nodeTypeLength ) {
  1803. // needed expand the input node
  1804. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1805. }
  1806. const nodeSnippet = node.build( builder, type );
  1807. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1808. // unnecessary swizzle
  1809. snippet = builder.format( nodeSnippet, type, output );
  1810. } else {
  1811. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1812. }
  1813. } else {
  1814. // ignore .components if .node returns float/integer
  1815. snippet = node.build( builder, output );
  1816. }
  1817. return snippet;
  1818. }
  1819. serialize( data ) {
  1820. super.serialize( data );
  1821. data.components = this.components;
  1822. }
  1823. deserialize( data ) {
  1824. super.deserialize( data );
  1825. this.components = data.components;
  1826. }
  1827. }
  1828. /**
  1829. * This module is part of the TSL core and usually not used in app level code.
  1830. * `SetNode` represents a set operation which means it is used to implement any
  1831. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1832. * For example:
  1833. * ```js
  1834. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1835. * ```
  1836. *
  1837. * @augments TempNode
  1838. */
  1839. class SetNode extends TempNode {
  1840. static get type() {
  1841. return 'SetNode';
  1842. }
  1843. /**
  1844. * Constructs a new set node.
  1845. *
  1846. * @param {Node} sourceNode - The node that should be updated.
  1847. * @param {string} components - The components that should be updated.
  1848. * @param {Node} targetNode - The value node.
  1849. */
  1850. constructor( sourceNode, components, targetNode ) {
  1851. super();
  1852. /**
  1853. * The node that should be updated.
  1854. *
  1855. * @type {Node}
  1856. */
  1857. this.sourceNode = sourceNode;
  1858. /**
  1859. * The components that should be updated.
  1860. *
  1861. * @type {string}
  1862. */
  1863. this.components = components;
  1864. /**
  1865. * The value node.
  1866. *
  1867. * @type {Node}
  1868. */
  1869. this.targetNode = targetNode;
  1870. }
  1871. /**
  1872. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1873. *
  1874. * @param {NodeBuilder} builder - The current node builder.
  1875. * @return {string} The node type.
  1876. */
  1877. getNodeType( builder ) {
  1878. return this.sourceNode.getNodeType( builder );
  1879. }
  1880. generate( builder ) {
  1881. const { sourceNode, components, targetNode } = this;
  1882. const sourceType = this.getNodeType( builder );
  1883. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1884. const targetType = builder.getTypeFromLength( components.length, componentType );
  1885. const targetSnippet = targetNode.build( builder, targetType );
  1886. const sourceSnippet = sourceNode.build( builder, sourceType );
  1887. const length = builder.getTypeLength( sourceType );
  1888. const snippetValues = [];
  1889. for ( let i = 0; i < length; i ++ ) {
  1890. const component = vectorComponents[ i ];
  1891. if ( component === components[ 0 ] ) {
  1892. snippetValues.push( targetSnippet );
  1893. i += components.length - 1;
  1894. } else {
  1895. snippetValues.push( sourceSnippet + '.' + component );
  1896. }
  1897. }
  1898. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1899. }
  1900. }
  1901. /**
  1902. * This module is part of the TSL core and usually not used in app level code.
  1903. * It represents a flip operation during the shader generation process
  1904. * meaning it flips normalized values with the following formula:
  1905. * ```
  1906. * x = 1 - x;
  1907. * ```
  1908. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1909. * `flipSTPQ()` method invocations on node objects. For example:
  1910. * ```js
  1911. * uvNode = uvNode.flipY();
  1912. * ```
  1913. *
  1914. * @augments TempNode
  1915. */
  1916. class FlipNode extends TempNode {
  1917. static get type() {
  1918. return 'FlipNode';
  1919. }
  1920. /**
  1921. * Constructs a new flip node.
  1922. *
  1923. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1924. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1925. */
  1926. constructor( sourceNode, components ) {
  1927. super();
  1928. /**
  1929. * The node which component(s) should be flipped.
  1930. *
  1931. * @type {Node}
  1932. */
  1933. this.sourceNode = sourceNode;
  1934. /**
  1935. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1936. *
  1937. * @type {string}
  1938. */
  1939. this.components = components;
  1940. }
  1941. /**
  1942. * This method is overwritten since the node type is inferred from the source node.
  1943. *
  1944. * @param {NodeBuilder} builder - The current node builder.
  1945. * @return {string} The node type.
  1946. */
  1947. getNodeType( builder ) {
  1948. return this.sourceNode.getNodeType( builder );
  1949. }
  1950. generate( builder ) {
  1951. const { components, sourceNode } = this;
  1952. const sourceType = this.getNodeType( builder );
  1953. const sourceSnippet = sourceNode.build( builder );
  1954. const sourceCache = builder.getVarFromNode( this );
  1955. const sourceProperty = builder.getPropertyName( sourceCache );
  1956. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1957. const length = builder.getTypeLength( sourceType );
  1958. const snippetValues = [];
  1959. let componentIndex = 0;
  1960. for ( let i = 0; i < length; i ++ ) {
  1961. const component = vectorComponents[ i ];
  1962. if ( component === components[ componentIndex ] ) {
  1963. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1964. componentIndex ++;
  1965. } else {
  1966. snippetValues.push( sourceProperty + '.' + component );
  1967. }
  1968. }
  1969. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1970. }
  1971. }
  1972. /**
  1973. * Base class for representing data input nodes.
  1974. *
  1975. * @augments Node
  1976. */
  1977. class InputNode extends Node {
  1978. static get type() {
  1979. return 'InputNode';
  1980. }
  1981. /**
  1982. * Constructs a new input node.
  1983. *
  1984. * @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).
  1985. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1986. */
  1987. constructor( value, nodeType = null ) {
  1988. super( nodeType );
  1989. /**
  1990. * This flag can be used for type testing.
  1991. *
  1992. * @type {boolean}
  1993. * @readonly
  1994. * @default true
  1995. */
  1996. this.isInputNode = true;
  1997. /**
  1998. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1999. *
  2000. * @type {any}
  2001. */
  2002. this.value = value;
  2003. /**
  2004. * The precision of the value in the shader.
  2005. *
  2006. * @type {?('low'|'medium'|'high')}
  2007. * @default null
  2008. */
  2009. this.precision = null;
  2010. }
  2011. getNodeType( /*builder*/ ) {
  2012. if ( this.nodeType === null ) {
  2013. return getValueType( this.value );
  2014. }
  2015. return this.nodeType;
  2016. }
  2017. /**
  2018. * Returns the input type of the node which is by default the node type. Derived modules
  2019. * might overwrite this method and use a fixed type or compute one analytically.
  2020. *
  2021. * A typical example for different input and node types are textures. The input type of a
  2022. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2023. *
  2024. * @param {NodeBuilder} builder - The current node builder.
  2025. * @return {string} The input type.
  2026. */
  2027. getInputType( builder ) {
  2028. return this.getNodeType( builder );
  2029. }
  2030. /**
  2031. * Sets the precision to the given value. The method can be
  2032. * overwritten in derived classes if the final precision must be computed
  2033. * analytically.
  2034. *
  2035. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2036. * @return {InputNode} A reference to this node.
  2037. */
  2038. setPrecision( precision ) {
  2039. this.precision = precision;
  2040. return this;
  2041. }
  2042. serialize( data ) {
  2043. super.serialize( data );
  2044. data.value = this.value;
  2045. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2046. data.valueType = getValueType( this.value );
  2047. data.nodeType = this.nodeType;
  2048. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2049. data.precision = this.precision;
  2050. }
  2051. deserialize( data ) {
  2052. super.deserialize( data );
  2053. this.nodeType = data.nodeType;
  2054. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2055. this.precision = data.precision || null;
  2056. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2057. }
  2058. generate( /*builder, output*/ ) {
  2059. console.warn( 'Abstract function.' );
  2060. }
  2061. }
  2062. const _regNum = /float|u?int/;
  2063. /**
  2064. * Class for representing a constant value in the shader.
  2065. *
  2066. * @augments InputNode
  2067. */
  2068. class ConstNode extends InputNode {
  2069. static get type() {
  2070. return 'ConstNode';
  2071. }
  2072. /**
  2073. * Constructs a new input node.
  2074. *
  2075. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2076. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2077. */
  2078. constructor( value, nodeType = null ) {
  2079. super( value, nodeType );
  2080. /**
  2081. * This flag can be used for type testing.
  2082. *
  2083. * @type {boolean}
  2084. * @readonly
  2085. * @default true
  2086. */
  2087. this.isConstNode = true;
  2088. }
  2089. /**
  2090. * Generates the shader string of the value with the current node builder.
  2091. *
  2092. * @param {NodeBuilder} builder - The current node builder.
  2093. * @return {string} The generated value as a shader string.
  2094. */
  2095. generateConst( builder ) {
  2096. return builder.generateConst( this.getNodeType( builder ), this.value );
  2097. }
  2098. generate( builder, output ) {
  2099. const type = this.getNodeType( builder );
  2100. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2101. return builder.generateConst( output, this.value );
  2102. }
  2103. return builder.format( this.generateConst( builder ), type, output );
  2104. }
  2105. }
  2106. /**
  2107. * Base class for representing member access on an object-like
  2108. * node data structures.
  2109. *
  2110. * @augments Node
  2111. */
  2112. class MemberNode extends Node {
  2113. static get type() {
  2114. return 'MemberNode';
  2115. }
  2116. /**
  2117. * Constructs an array element node.
  2118. *
  2119. * @param {Node} node - The array-like node.
  2120. * @param {string} property - The property name.
  2121. */
  2122. constructor( node, property ) {
  2123. super();
  2124. /**
  2125. * The array-like node.
  2126. *
  2127. * @type {Node}
  2128. */
  2129. this.node = node;
  2130. /**
  2131. * The property name.
  2132. *
  2133. * @type {Node}
  2134. */
  2135. this.property = property;
  2136. /**
  2137. * This flag can be used for type testing.
  2138. *
  2139. * @type {boolean}
  2140. * @readonly
  2141. * @default true
  2142. */
  2143. this.isMemberNode = true;
  2144. }
  2145. getNodeType( builder ) {
  2146. return this.node.getMemberType( builder, this.property );
  2147. }
  2148. generate( builder ) {
  2149. const propertyName = this.node.build( builder );
  2150. return propertyName + '.' + this.property;
  2151. }
  2152. }
  2153. let currentStack = null;
  2154. const NodeElements = new Map();
  2155. function addMethodChaining( name, nodeElement ) {
  2156. if ( NodeElements.has( name ) ) {
  2157. console.warn( `THREE.TSL: Redefinition of method chaining '${ name }'.` );
  2158. return;
  2159. }
  2160. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2161. NodeElements.set( name, nodeElement );
  2162. }
  2163. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2164. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2165. const shaderNodeHandler = {
  2166. setup( NodeClosure, params ) {
  2167. const inputs = params.shift();
  2168. return NodeClosure( nodeObjects( inputs ), ...params );
  2169. },
  2170. get( node, prop, nodeObj ) {
  2171. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2172. if ( node.isStackNode !== true && prop === 'assign' ) {
  2173. return ( ...params ) => {
  2174. currentStack.assign( nodeObj, ...params );
  2175. return nodeObj;
  2176. };
  2177. } else if ( NodeElements.has( prop ) ) {
  2178. const nodeElement = NodeElements.get( prop );
  2179. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2180. } else if ( prop === 'toVarIntent' ) {
  2181. return () => nodeObj;
  2182. } else if ( prop === 'self' ) {
  2183. return node;
  2184. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2185. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2186. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2187. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2188. // accessing properties ( swizzle )
  2189. prop = parseSwizzle( prop );
  2190. return nodeObject( new SplitNode( nodeObj, prop ) );
  2191. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2192. // set properties ( swizzle ) and sort to xyzw sequence
  2193. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2194. return ( value ) => nodeObject( new SetNode( node, prop, nodeObject( value ) ) );
  2195. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2196. // set properties ( swizzle ) and sort to xyzw sequence
  2197. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2198. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2199. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2200. // accessing property
  2201. if ( prop === 'width' ) prop = 'x';
  2202. else if ( prop === 'height' ) prop = 'y';
  2203. else if ( prop === 'depth' ) prop = 'z';
  2204. return nodeObject( new SplitNode( node, prop ) );
  2205. } else if ( /^\d+$/.test( prop ) === true ) {
  2206. // accessing array
  2207. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2208. } else if ( /^get$/.test( prop ) === true ) {
  2209. // accessing properties
  2210. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2211. }
  2212. }
  2213. return Reflect.get( node, prop, nodeObj );
  2214. },
  2215. set( node, prop, value, nodeObj ) {
  2216. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2217. // setting properties
  2218. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2219. nodeObj[ prop ].assign( value );
  2220. return true;
  2221. }
  2222. }
  2223. return Reflect.set( node, prop, value, nodeObj );
  2224. }
  2225. };
  2226. const nodeObjectsCacheMap = new WeakMap();
  2227. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2228. const ShaderNodeObject = function ( obj, altType = null ) {
  2229. const type = getValueType( obj );
  2230. if ( type === 'node' ) {
  2231. let nodeObject = nodeObjectsCacheMap.get( obj );
  2232. if ( nodeObject === undefined ) {
  2233. nodeObject = new Proxy( obj, shaderNodeHandler );
  2234. nodeObjectsCacheMap.set( obj, nodeObject );
  2235. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2236. }
  2237. return nodeObject;
  2238. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2239. return nodeObject( getConstNode( obj, altType ) );
  2240. } else if ( type === 'shader' ) {
  2241. return obj.isFn ? obj : Fn( obj );
  2242. }
  2243. return obj;
  2244. };
  2245. const ShaderNodeObjects = function ( objects, altType = null ) {
  2246. for ( const name in objects ) {
  2247. objects[ name ] = nodeObject( objects[ name ], altType );
  2248. }
  2249. return objects;
  2250. };
  2251. const ShaderNodeArray = function ( array, altType = null ) {
  2252. const len = array.length;
  2253. for ( let i = 0; i < len; i ++ ) {
  2254. array[ i ] = nodeObject( array[ i ], altType );
  2255. }
  2256. return array;
  2257. };
  2258. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2259. function assignNode( node ) {
  2260. if ( settings !== null ) {
  2261. node = nodeObject( Object.assign( node, settings ) );
  2262. if ( settings.intent === true ) {
  2263. node = node.toVarIntent();
  2264. }
  2265. } else {
  2266. node = nodeObject( node );
  2267. }
  2268. return node;
  2269. }
  2270. let fn, name = scope, minParams, maxParams;
  2271. function verifyParamsLimit( params ) {
  2272. let tslName;
  2273. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2274. else tslName = NodeClass.type;
  2275. if ( minParams !== undefined && params.length < minParams ) {
  2276. console.error( `THREE.TSL: "${ tslName }" parameter length is less than minimum required.` );
  2277. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2278. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2279. console.error( `THREE.TSL: "${ tslName }" parameter length exceeds limit.` );
  2280. return params.slice( 0, maxParams );
  2281. }
  2282. return params;
  2283. }
  2284. if ( scope === null ) {
  2285. fn = ( ...params ) => {
  2286. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2287. };
  2288. } else if ( factor !== null ) {
  2289. factor = nodeObject( factor );
  2290. fn = ( ...params ) => {
  2291. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2292. };
  2293. } else {
  2294. fn = ( ...params ) => {
  2295. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2296. };
  2297. }
  2298. fn.setParameterLength = ( ...params ) => {
  2299. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2300. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2301. return fn;
  2302. };
  2303. fn.setName = ( value ) => {
  2304. name = value;
  2305. return fn;
  2306. };
  2307. return fn;
  2308. };
  2309. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2310. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2311. };
  2312. class ShaderCallNodeInternal extends Node {
  2313. constructor( shaderNode, inputNodes ) {
  2314. super();
  2315. this.shaderNode = shaderNode;
  2316. this.inputNodes = inputNodes;
  2317. this.isShaderCallNodeInternal = true;
  2318. }
  2319. getNodeType( builder ) {
  2320. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2321. }
  2322. getMemberType( builder, name ) {
  2323. return this.getOutputNode( builder ).getMemberType( builder, name );
  2324. }
  2325. call( builder ) {
  2326. const { shaderNode, inputNodes } = this;
  2327. const properties = builder.getNodeProperties( shaderNode );
  2328. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2329. const subBuildProperty = subBuild || 'default';
  2330. if ( properties[ subBuildProperty ] ) {
  2331. return properties[ subBuildProperty ];
  2332. }
  2333. //
  2334. const previousSubBuildFn = builder.subBuildFn;
  2335. builder.subBuildFn = subBuild;
  2336. let result = null;
  2337. if ( shaderNode.layout ) {
  2338. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2339. if ( functionNodesCacheMap === undefined ) {
  2340. functionNodesCacheMap = new WeakMap();
  2341. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2342. }
  2343. let functionNode = functionNodesCacheMap.get( shaderNode );
  2344. if ( functionNode === undefined ) {
  2345. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2346. functionNodesCacheMap.set( shaderNode, functionNode );
  2347. }
  2348. builder.addInclude( functionNode );
  2349. result = nodeObject( functionNode.call( inputNodes ) );
  2350. } else {
  2351. let inputs = inputNodes;
  2352. if ( Array.isArray( inputs ) ) {
  2353. // If inputs is an array, we need to convert it to a Proxy
  2354. // so we can call TSL functions using the syntax `Fn( ( { r, g, b } ) => { ... } )`
  2355. // and call through `fn( 0, 1, 0 )` or `fn( { r: 0, g: 1, b: 0 } )`
  2356. let index = 0;
  2357. inputs = new Proxy( inputs, {
  2358. get: ( target, property, receiver ) => {
  2359. if ( target[ property ] === undefined ) {
  2360. return target[ index ++ ];
  2361. } else {
  2362. return Reflect.get( target, property, receiver );
  2363. }
  2364. }
  2365. } );
  2366. }
  2367. const jsFunc = shaderNode.jsFunc;
  2368. const outputNode = inputs !== null || jsFunc.length > 1 ? jsFunc( inputs || [], builder ) : jsFunc( builder );
  2369. result = nodeObject( outputNode );
  2370. }
  2371. builder.subBuildFn = previousSubBuildFn;
  2372. if ( shaderNode.once ) {
  2373. properties[ subBuildProperty ] = result;
  2374. }
  2375. return result;
  2376. }
  2377. setupOutput( builder ) {
  2378. builder.addStack();
  2379. builder.stack.outputNode = this.call( builder );
  2380. return builder.removeStack();
  2381. }
  2382. getOutputNode( builder ) {
  2383. const properties = builder.getNodeProperties( this );
  2384. const subBuildOutput = builder.getSubBuildOutput( this );
  2385. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2386. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2387. return properties[ subBuildOutput ];
  2388. }
  2389. build( builder, output = null ) {
  2390. let result = null;
  2391. const buildStage = builder.getBuildStage();
  2392. const properties = builder.getNodeProperties( this );
  2393. const subBuildOutput = builder.getSubBuildOutput( this );
  2394. const outputNode = this.getOutputNode( builder );
  2395. if ( buildStage === 'setup' ) {
  2396. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2397. if ( properties[ subBuildInitialized ] !== true ) {
  2398. properties[ subBuildInitialized ] = true;
  2399. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2400. properties[ subBuildOutput ].build( builder );
  2401. // If the shaderNode has subBuilds, add them to the chaining nodes
  2402. // so they can be built later in the build process.
  2403. if ( this.shaderNode.subBuilds ) {
  2404. for ( const node of builder.chaining ) {
  2405. const nodeData = builder.getDataFromNode( node, 'any' );
  2406. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2407. for ( const subBuild of this.shaderNode.subBuilds ) {
  2408. nodeData.subBuilds.add( subBuild );
  2409. }
  2410. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2411. }
  2412. }
  2413. }
  2414. result = properties[ subBuildOutput ];
  2415. } else if ( buildStage === 'analyze' ) {
  2416. outputNode.build( builder, output );
  2417. } else if ( buildStage === 'generate' ) {
  2418. result = outputNode.build( builder, output ) || '';
  2419. }
  2420. return result;
  2421. }
  2422. }
  2423. class ShaderNodeInternal extends Node {
  2424. constructor( jsFunc, nodeType ) {
  2425. super( nodeType );
  2426. this.jsFunc = jsFunc;
  2427. this.layout = null;
  2428. this.global = true;
  2429. this.once = false;
  2430. }
  2431. setLayout( layout ) {
  2432. this.layout = layout;
  2433. return this;
  2434. }
  2435. call( inputs = null ) {
  2436. nodeObjects( inputs );
  2437. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2438. }
  2439. setup() {
  2440. return this.call();
  2441. }
  2442. }
  2443. const bools = [ false, true ];
  2444. const uints = [ 0, 1, 2, 3 ];
  2445. const ints = [ -1, -2 ];
  2446. 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 ];
  2447. const boolsCacheMap = new Map();
  2448. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2449. const uintsCacheMap = new Map();
  2450. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2451. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2452. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2453. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2454. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2455. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2456. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2457. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2458. const getConstNode = ( value, type ) => {
  2459. if ( constNodesCacheMap.has( value ) ) {
  2460. return constNodesCacheMap.get( value );
  2461. } else if ( value.isNode === true ) {
  2462. return value;
  2463. } else {
  2464. return new ConstNode( value, type );
  2465. }
  2466. };
  2467. const ConvertType = function ( type, cacheMap = null ) {
  2468. return ( ...params ) => {
  2469. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2470. params = [ getValueFromType( type, ...params ) ];
  2471. }
  2472. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2473. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2474. }
  2475. if ( params.length === 1 ) {
  2476. const node = getConstNode( params[ 0 ], type );
  2477. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2478. return nodeObjectIntent( new ConvertNode( node, type ) );
  2479. }
  2480. const nodes = params.map( param => getConstNode( param ) );
  2481. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2482. };
  2483. };
  2484. // exports
  2485. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2486. // utils
  2487. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2488. // shader node base
  2489. function ShaderNode( jsFunc, nodeType ) {
  2490. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2491. }
  2492. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2493. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2494. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2495. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2496. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2497. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2498. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { intent: true, ...settings } );
  2499. let fnId = 0;
  2500. const Fn = ( jsFunc, layout = null ) => {
  2501. let nodeType = null;
  2502. if ( layout !== null ) {
  2503. if ( typeof layout === 'object' ) {
  2504. nodeType = layout.return;
  2505. } else {
  2506. if ( typeof layout === 'string' ) {
  2507. nodeType = layout;
  2508. } else {
  2509. console.error( 'THREE.TSL: Invalid layout type.' );
  2510. }
  2511. layout = null;
  2512. }
  2513. }
  2514. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2515. const fn = ( ...params ) => {
  2516. let inputs;
  2517. nodeObjects( params );
  2518. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2519. if ( isArrayAsParameter ) {
  2520. inputs = [ ...params ];
  2521. } else {
  2522. inputs = params[ 0 ];
  2523. }
  2524. const fnCall = shaderNode.call( inputs );
  2525. if ( nodeType === 'void' ) fnCall.toStack();
  2526. return fnCall.toVarIntent();
  2527. };
  2528. fn.shaderNode = shaderNode;
  2529. fn.id = shaderNode.id;
  2530. fn.isFn = true;
  2531. fn.getNodeType = ( ...params ) => shaderNode.getNodeType( ...params );
  2532. fn.getCacheKey = ( ...params ) => shaderNode.getCacheKey( ...params );
  2533. fn.setLayout = ( layout ) => {
  2534. shaderNode.setLayout( layout );
  2535. return fn;
  2536. };
  2537. fn.once = ( subBuilds = null ) => {
  2538. shaderNode.once = true;
  2539. shaderNode.subBuilds = subBuilds;
  2540. return fn;
  2541. };
  2542. if ( layout !== null ) {
  2543. if ( typeof layout.inputs !== 'object' ) {
  2544. const fullLayout = {
  2545. name: 'fn' + fnId ++,
  2546. type: nodeType,
  2547. inputs: []
  2548. };
  2549. for ( const name in layout ) {
  2550. if ( name === 'return' ) continue;
  2551. fullLayout.inputs.push( {
  2552. name: name,
  2553. type: layout[ name ]
  2554. } );
  2555. }
  2556. layout = fullLayout;
  2557. }
  2558. fn.setLayout( layout );
  2559. }
  2560. return fn;
  2561. };
  2562. //
  2563. const setCurrentStack = ( stack ) => {
  2564. currentStack = stack;
  2565. };
  2566. const getCurrentStack = () => currentStack;
  2567. /**
  2568. * Represent a conditional node using if/else statements.
  2569. *
  2570. * ```js
  2571. * If( condition, function )
  2572. * .ElseIf( condition, function )
  2573. * .Else( function )
  2574. * ```
  2575. * @tsl
  2576. * @function
  2577. * @param {...any} params - The parameters for the conditional node.
  2578. * @returns {StackNode} The conditional node.
  2579. */
  2580. const If = ( ...params ) => currentStack.If( ...params );
  2581. /**
  2582. * Represent a conditional node using switch/case statements.
  2583. *
  2584. * ```js
  2585. * Switch( value )
  2586. * .Case( 1, function )
  2587. * .Case( 2, 3, 4, function )
  2588. * .Default( function )
  2589. * ```
  2590. * @tsl
  2591. * @function
  2592. * @param {...any} params - The parameters for the conditional node.
  2593. * @returns {StackNode} The conditional node.
  2594. */
  2595. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2596. /**
  2597. * Add the given node to the current stack.
  2598. *
  2599. * @param {Node} node - The node to add.
  2600. * @returns {Node} The node that was added to the stack.
  2601. */
  2602. function Stack( node ) {
  2603. if ( currentStack ) currentStack.add( node );
  2604. return node;
  2605. }
  2606. addMethodChaining( 'toStack', Stack );
  2607. // types
  2608. const color = new ConvertType( 'color' );
  2609. const float = new ConvertType( 'float', cacheMaps.float );
  2610. const int = new ConvertType( 'int', cacheMaps.ints );
  2611. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2612. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2613. const vec2 = new ConvertType( 'vec2' );
  2614. const ivec2 = new ConvertType( 'ivec2' );
  2615. const uvec2 = new ConvertType( 'uvec2' );
  2616. const bvec2 = new ConvertType( 'bvec2' );
  2617. const vec3 = new ConvertType( 'vec3' );
  2618. const ivec3 = new ConvertType( 'ivec3' );
  2619. const uvec3 = new ConvertType( 'uvec3' );
  2620. const bvec3 = new ConvertType( 'bvec3' );
  2621. const vec4 = new ConvertType( 'vec4' );
  2622. const ivec4 = new ConvertType( 'ivec4' );
  2623. const uvec4 = new ConvertType( 'uvec4' );
  2624. const bvec4 = new ConvertType( 'bvec4' );
  2625. const mat2 = new ConvertType( 'mat2' );
  2626. const mat3 = new ConvertType( 'mat3' );
  2627. const mat4 = new ConvertType( 'mat4' );
  2628. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2629. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2630. addMethodChaining( 'toColor', color );
  2631. addMethodChaining( 'toFloat', float );
  2632. addMethodChaining( 'toInt', int );
  2633. addMethodChaining( 'toUint', uint );
  2634. addMethodChaining( 'toBool', bool );
  2635. addMethodChaining( 'toVec2', vec2 );
  2636. addMethodChaining( 'toIVec2', ivec2 );
  2637. addMethodChaining( 'toUVec2', uvec2 );
  2638. addMethodChaining( 'toBVec2', bvec2 );
  2639. addMethodChaining( 'toVec3', vec3 );
  2640. addMethodChaining( 'toIVec3', ivec3 );
  2641. addMethodChaining( 'toUVec3', uvec3 );
  2642. addMethodChaining( 'toBVec3', bvec3 );
  2643. addMethodChaining( 'toVec4', vec4 );
  2644. addMethodChaining( 'toIVec4', ivec4 );
  2645. addMethodChaining( 'toUVec4', uvec4 );
  2646. addMethodChaining( 'toBVec4', bvec4 );
  2647. addMethodChaining( 'toMat2', mat2 );
  2648. addMethodChaining( 'toMat3', mat3 );
  2649. addMethodChaining( 'toMat4', mat4 );
  2650. // basic nodes
  2651. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2652. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2653. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2654. addMethodChaining( 'element', element );
  2655. addMethodChaining( 'convert', convert );
  2656. // deprecated
  2657. /**
  2658. * @tsl
  2659. * @function
  2660. * @deprecated since r176. Use {@link Stack} instead.
  2661. *
  2662. * @param {Node} node - The node to add.
  2663. * @returns {Function}
  2664. */
  2665. const append = ( node ) => { // @deprecated, r176
  2666. console.warn( 'THREE.TSL: append() has been renamed to Stack().' );
  2667. return Stack( node );
  2668. };
  2669. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2670. console.warn( 'THREE.TSL: .append() has been renamed to .toStack().' );
  2671. return Stack( node );
  2672. } );
  2673. /**
  2674. * This class represents a shader property. It can be used
  2675. * to explicitly define a property and assign a value to it.
  2676. *
  2677. * ```js
  2678. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2679. *```
  2680. * `PropertyNode` is used by the engine to predefined common material properties
  2681. * for TSL code.
  2682. *
  2683. * @augments Node
  2684. */
  2685. class PropertyNode extends Node {
  2686. static get type() {
  2687. return 'PropertyNode';
  2688. }
  2689. /**
  2690. * Constructs a new property node.
  2691. *
  2692. * @param {string} nodeType - The type of the node.
  2693. * @param {?string} [name=null] - The name of the property in the shader.
  2694. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2695. */
  2696. constructor( nodeType, name = null, varying = false ) {
  2697. super( nodeType );
  2698. /**
  2699. * The name of the property in the shader. If no name is defined,
  2700. * the node system auto-generates one.
  2701. *
  2702. * @type {?string}
  2703. * @default null
  2704. */
  2705. this.name = name;
  2706. /**
  2707. * Whether this property is a varying or not.
  2708. *
  2709. * @type {boolean}
  2710. * @default false
  2711. */
  2712. this.varying = varying;
  2713. /**
  2714. * This flag can be used for type testing.
  2715. *
  2716. * @type {boolean}
  2717. * @readonly
  2718. * @default true
  2719. */
  2720. this.isPropertyNode = true;
  2721. /**
  2722. * This flag is used for global cache.
  2723. *
  2724. * @type {boolean}
  2725. * @default true
  2726. */
  2727. this.global = true;
  2728. }
  2729. getHash( builder ) {
  2730. return this.name || super.getHash( builder );
  2731. }
  2732. generate( builder ) {
  2733. let nodeVar;
  2734. if ( this.varying === true ) {
  2735. nodeVar = builder.getVaryingFromNode( this, this.name );
  2736. nodeVar.needsInterpolation = true;
  2737. } else {
  2738. nodeVar = builder.getVarFromNode( this, this.name );
  2739. }
  2740. return builder.getPropertyName( nodeVar );
  2741. }
  2742. }
  2743. /**
  2744. * TSL function for creating a property node.
  2745. *
  2746. * @tsl
  2747. * @function
  2748. * @param {string} type - The type of the node.
  2749. * @param {?string} [name=null] - The name of the property in the shader.
  2750. * @returns {PropertyNode}
  2751. */
  2752. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2753. /**
  2754. * TSL function for creating a varying property node.
  2755. *
  2756. * @tsl
  2757. * @function
  2758. * @param {string} type - The type of the node.
  2759. * @param {?string} [name=null] - The name of the varying in the shader.
  2760. * @returns {PropertyNode}
  2761. */
  2762. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2763. /**
  2764. * TSL object that represents the shader variable `DiffuseColor`.
  2765. *
  2766. * @tsl
  2767. * @type {PropertyNode<vec4>}
  2768. */
  2769. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2770. /**
  2771. * TSL object that represents the shader variable `EmissiveColor`.
  2772. *
  2773. * @tsl
  2774. * @type {PropertyNode<vec3>}
  2775. */
  2776. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2777. /**
  2778. * TSL object that represents the shader variable `Roughness`.
  2779. *
  2780. * @tsl
  2781. * @type {PropertyNode<float>}
  2782. */
  2783. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2784. /**
  2785. * TSL object that represents the shader variable `Metalness`.
  2786. *
  2787. * @tsl
  2788. * @type {PropertyNode<float>}
  2789. */
  2790. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2791. /**
  2792. * TSL object that represents the shader variable `Clearcoat`.
  2793. *
  2794. * @tsl
  2795. * @type {PropertyNode<float>}
  2796. */
  2797. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2798. /**
  2799. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2800. *
  2801. * @tsl
  2802. * @type {PropertyNode<float>}
  2803. */
  2804. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2805. /**
  2806. * TSL object that represents the shader variable `Sheen`.
  2807. *
  2808. * @tsl
  2809. * @type {PropertyNode<vec3>}
  2810. */
  2811. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2812. /**
  2813. * TSL object that represents the shader variable `SheenRoughness`.
  2814. *
  2815. * @tsl
  2816. * @type {PropertyNode<float>}
  2817. */
  2818. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2819. /**
  2820. * TSL object that represents the shader variable `Iridescence`.
  2821. *
  2822. * @tsl
  2823. * @type {PropertyNode<float>}
  2824. */
  2825. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2826. /**
  2827. * TSL object that represents the shader variable `IridescenceIOR`.
  2828. *
  2829. * @tsl
  2830. * @type {PropertyNode<float>}
  2831. */
  2832. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2833. /**
  2834. * TSL object that represents the shader variable `IridescenceThickness`.
  2835. *
  2836. * @tsl
  2837. * @type {PropertyNode<float>}
  2838. */
  2839. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2840. /**
  2841. * TSL object that represents the shader variable `AlphaT`.
  2842. *
  2843. * @tsl
  2844. * @type {PropertyNode<float>}
  2845. */
  2846. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2847. /**
  2848. * TSL object that represents the shader variable `Anisotropy`.
  2849. *
  2850. * @tsl
  2851. * @type {PropertyNode<float>}
  2852. */
  2853. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2854. /**
  2855. * TSL object that represents the shader variable `AnisotropyT`.
  2856. *
  2857. * @tsl
  2858. * @type {PropertyNode<vec3>}
  2859. */
  2860. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2861. /**
  2862. * TSL object that represents the shader variable `AnisotropyB`.
  2863. *
  2864. * @tsl
  2865. * @type {PropertyNode<vec3>}
  2866. */
  2867. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2868. /**
  2869. * TSL object that represents the shader variable `SpecularColor`.
  2870. *
  2871. * @tsl
  2872. * @type {PropertyNode<color>}
  2873. */
  2874. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2875. /**
  2876. * TSL object that represents the shader variable `SpecularF90`.
  2877. *
  2878. * @tsl
  2879. * @type {PropertyNode<float>}
  2880. */
  2881. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2882. /**
  2883. * TSL object that represents the shader variable `Shininess`.
  2884. *
  2885. * @tsl
  2886. * @type {PropertyNode<float>}
  2887. */
  2888. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2889. /**
  2890. * TSL object that represents the shader variable `Output`.
  2891. *
  2892. * @tsl
  2893. * @type {PropertyNode<vec4>}
  2894. */
  2895. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2896. /**
  2897. * TSL object that represents the shader variable `dashSize`.
  2898. *
  2899. * @tsl
  2900. * @type {PropertyNode<float>}
  2901. */
  2902. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2903. /**
  2904. * TSL object that represents the shader variable `gapSize`.
  2905. *
  2906. * @tsl
  2907. * @type {PropertyNode<float>}
  2908. */
  2909. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2910. /**
  2911. * TSL object that represents the shader variable `pointWidth`.
  2912. *
  2913. * @tsl
  2914. * @type {PropertyNode<float>}
  2915. */
  2916. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2917. /**
  2918. * TSL object that represents the shader variable `IOR`.
  2919. *
  2920. * @tsl
  2921. * @type {PropertyNode<float>}
  2922. */
  2923. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2924. /**
  2925. * TSL object that represents the shader variable `Transmission`.
  2926. *
  2927. * @tsl
  2928. * @type {PropertyNode<float>}
  2929. */
  2930. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2931. /**
  2932. * TSL object that represents the shader variable `Thickness`.
  2933. *
  2934. * @tsl
  2935. * @type {PropertyNode<float>}
  2936. */
  2937. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2938. /**
  2939. * TSL object that represents the shader variable `AttenuationDistance`.
  2940. *
  2941. * @tsl
  2942. * @type {PropertyNode<float>}
  2943. */
  2944. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2945. /**
  2946. * TSL object that represents the shader variable `AttenuationColor`.
  2947. *
  2948. * @tsl
  2949. * @type {PropertyNode<color>}
  2950. */
  2951. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2952. /**
  2953. * TSL object that represents the shader variable `Dispersion`.
  2954. *
  2955. * @tsl
  2956. * @type {PropertyNode<float>}
  2957. */
  2958. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2959. /**
  2960. * This node can be used to group single instances of {@link UniformNode}
  2961. * and manage them as a uniform buffer.
  2962. *
  2963. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2964. * will be used when defining the {@link UniformNode#groupNode} property.
  2965. *
  2966. * - `objectGroup`: Uniform buffer per object.
  2967. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2968. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2969. *
  2970. * @augments Node
  2971. */
  2972. class UniformGroupNode extends Node {
  2973. static get type() {
  2974. return 'UniformGroupNode';
  2975. }
  2976. /**
  2977. * Constructs a new uniform group node.
  2978. *
  2979. * @param {string} name - The name of the uniform group node.
  2980. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  2981. * @param {number} [order=1] - Influences the internal sorting.
  2982. */
  2983. constructor( name, shared = false, order = 1 ) {
  2984. super( 'string' );
  2985. /**
  2986. * The name of the uniform group node.
  2987. *
  2988. * @type {string}
  2989. */
  2990. this.name = name;
  2991. /**
  2992. * Whether this uniform group node is shared or not.
  2993. *
  2994. * @type {boolean}
  2995. * @default false
  2996. */
  2997. this.shared = shared;
  2998. /**
  2999. * Influences the internal sorting.
  3000. * TODO: Add details when this property should be changed.
  3001. *
  3002. * @type {number}
  3003. * @default 1
  3004. */
  3005. this.order = order;
  3006. /**
  3007. * This flag can be used for type testing.
  3008. *
  3009. * @type {boolean}
  3010. * @readonly
  3011. * @default true
  3012. */
  3013. this.isUniformGroup = true;
  3014. }
  3015. serialize( data ) {
  3016. super.serialize( data );
  3017. data.name = this.name;
  3018. data.version = this.version;
  3019. data.shared = this.shared;
  3020. }
  3021. deserialize( data ) {
  3022. super.deserialize( data );
  3023. this.name = data.name;
  3024. this.version = data.version;
  3025. this.shared = data.shared;
  3026. }
  3027. }
  3028. /**
  3029. * TSL function for creating a uniform group node with the given name.
  3030. *
  3031. * @tsl
  3032. * @function
  3033. * @param {string} name - The name of the uniform group node.
  3034. * @returns {UniformGroupNode}
  3035. */
  3036. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3037. /**
  3038. * TSL function for creating a shared uniform group node with the given name and order.
  3039. *
  3040. * @tsl
  3041. * @function
  3042. * @param {string} name - The name of the uniform group node.
  3043. * @param {number} [order=0] - Influences the internal sorting.
  3044. * @returns {UniformGroupNode}
  3045. */
  3046. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3047. /**
  3048. * TSL object that represents a shared uniform group node which is updated once per frame.
  3049. *
  3050. * @tsl
  3051. * @type {UniformGroupNode}
  3052. */
  3053. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3054. /**
  3055. * TSL object that represents a shared uniform group node which is updated once per render.
  3056. *
  3057. * @tsl
  3058. * @type {UniformGroupNode}
  3059. */
  3060. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3061. /**
  3062. * TSL object that represents a uniform group node which is updated once per object.
  3063. *
  3064. * @tsl
  3065. * @type {UniformGroupNode}
  3066. */
  3067. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3068. /**
  3069. * Class for representing a uniform.
  3070. *
  3071. * @augments InputNode
  3072. */
  3073. class UniformNode extends InputNode {
  3074. static get type() {
  3075. return 'UniformNode';
  3076. }
  3077. /**
  3078. * Constructs a new uniform node.
  3079. *
  3080. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3081. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3082. */
  3083. constructor( value, nodeType = null ) {
  3084. super( value, nodeType );
  3085. /**
  3086. * This flag can be used for type testing.
  3087. *
  3088. * @type {boolean}
  3089. * @readonly
  3090. * @default true
  3091. */
  3092. this.isUniformNode = true;
  3093. /**
  3094. * The name or label of the uniform.
  3095. *
  3096. * @type {string}
  3097. * @default ''
  3098. */
  3099. this.name = '';
  3100. /**
  3101. * The uniform group of this uniform. By default, uniforms are
  3102. * managed per object but they might belong to a shared group
  3103. * which is updated per frame or render call.
  3104. *
  3105. * @type {UniformGroupNode}
  3106. */
  3107. this.groupNode = objectGroup;
  3108. }
  3109. /**
  3110. * Sets the {@link UniformNode#name} property.
  3111. *
  3112. * @param {string} name - The name of the uniform.
  3113. * @return {UniformNode} A reference to this node.
  3114. */
  3115. setName( name ) {
  3116. this.name = name;
  3117. return this;
  3118. }
  3119. /**
  3120. * Sets the {@link UniformNode#name} property.
  3121. *
  3122. * @deprecated
  3123. * @param {string} name - The name of the uniform.
  3124. * @return {UniformNode} A reference to this node.
  3125. */
  3126. label( name ) {
  3127. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3128. return this.setName( name );
  3129. }
  3130. /**
  3131. * Sets the {@link UniformNode#groupNode} property.
  3132. *
  3133. * @param {UniformGroupNode} group - The uniform group.
  3134. * @return {UniformNode} A reference to this node.
  3135. */
  3136. setGroup( group ) {
  3137. this.groupNode = group;
  3138. return this;
  3139. }
  3140. /**
  3141. * Returns the {@link UniformNode#groupNode}.
  3142. *
  3143. * @return {UniformGroupNode} The uniform group.
  3144. */
  3145. getGroup() {
  3146. return this.groupNode;
  3147. }
  3148. /**
  3149. * By default, this method returns the result of {@link Node#getHash} but derived
  3150. * classes might overwrite this method with a different implementation.
  3151. *
  3152. * @param {NodeBuilder} builder - The current node builder.
  3153. * @return {string} The uniform hash.
  3154. */
  3155. getUniformHash( builder ) {
  3156. return this.getHash( builder );
  3157. }
  3158. onUpdate( callback, updateType ) {
  3159. const self = this.getSelf();
  3160. callback = callback.bind( self );
  3161. return super.onUpdate( ( frame ) => {
  3162. const value = callback( frame, self );
  3163. if ( value !== undefined ) {
  3164. this.value = value;
  3165. }
  3166. }, updateType );
  3167. }
  3168. getInputType( builder ) {
  3169. let type = super.getInputType( builder );
  3170. if ( type === 'bool' ) {
  3171. type = 'uint';
  3172. }
  3173. return type;
  3174. }
  3175. generate( builder, output ) {
  3176. const type = this.getNodeType( builder );
  3177. const hash = this.getUniformHash( builder );
  3178. let sharedNode = builder.getNodeFromHash( hash );
  3179. if ( sharedNode === undefined ) {
  3180. builder.setHashNode( this, hash );
  3181. sharedNode = this;
  3182. }
  3183. const sharedNodeType = sharedNode.getInputType( builder );
  3184. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  3185. const uniformName = builder.getPropertyName( nodeUniform );
  3186. if ( builder.context.label !== undefined ) delete builder.context.label;
  3187. //
  3188. let snippet = uniformName;
  3189. if ( type === 'bool' ) {
  3190. // cache to variable
  3191. const nodeData = builder.getDataFromNode( this );
  3192. let propertyName = nodeData.propertyName;
  3193. if ( propertyName === undefined ) {
  3194. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3195. propertyName = builder.getPropertyName( nodeVar );
  3196. nodeData.propertyName = propertyName;
  3197. snippet = builder.format( uniformName, sharedNodeType, type );
  3198. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3199. }
  3200. snippet = propertyName;
  3201. }
  3202. return builder.format( snippet, type, output );
  3203. }
  3204. }
  3205. /**
  3206. * TSL function for creating a uniform node.
  3207. *
  3208. * @tsl
  3209. * @function
  3210. * @param {any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3211. * @param {string} [arg2] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3212. * @returns {UniformNode}
  3213. */
  3214. const uniform = ( arg1, arg2 ) => {
  3215. const nodeType = getConstNodeType( arg2 || arg1 );
  3216. // @TODO: get ConstNode from .traverse() in the future
  3217. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  3218. return nodeObject( new UniformNode( value, nodeType ) );
  3219. };
  3220. /**
  3221. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3222. * ```js
  3223. * const colors = array( [
  3224. * vec3( 1, 0, 0 ),
  3225. * vec3( 0, 1, 0 ),
  3226. * vec3( 0, 0, 1 )
  3227. * ] );
  3228. *
  3229. * const redColor = tintColors.element( 0 );
  3230. *
  3231. * @augments TempNode
  3232. */
  3233. class ArrayNode extends TempNode {
  3234. static get type() {
  3235. return 'ArrayNode';
  3236. }
  3237. /**
  3238. * Constructs a new array node.
  3239. *
  3240. * @param {?string} nodeType - The data type of the elements.
  3241. * @param {number} count - Size of the array.
  3242. * @param {?Array<Node>} [values=null] - Array default values.
  3243. */
  3244. constructor( nodeType, count, values = null ) {
  3245. super( nodeType );
  3246. /**
  3247. * Array size.
  3248. *
  3249. * @type {number}
  3250. */
  3251. this.count = count;
  3252. /**
  3253. * Array default values.
  3254. *
  3255. * @type {?Array<Node>}
  3256. */
  3257. this.values = values;
  3258. /**
  3259. * This flag can be used for type testing.
  3260. *
  3261. * @type {boolean}
  3262. * @readonly
  3263. * @default true
  3264. */
  3265. this.isArrayNode = true;
  3266. }
  3267. /**
  3268. * Returns the number of elements in the node array.
  3269. *
  3270. * @param {NodeBuilder} builder - The current node builder.
  3271. * @return {number} The number of elements in the node array.
  3272. */
  3273. getArrayCount( /*builder*/ ) {
  3274. return this.count;
  3275. }
  3276. /**
  3277. * Returns the node's type.
  3278. *
  3279. * @param {NodeBuilder} builder - The current node builder.
  3280. * @return {string} The type of the node.
  3281. */
  3282. getNodeType( builder ) {
  3283. if ( this.nodeType === null ) {
  3284. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3285. }
  3286. return this.nodeType;
  3287. }
  3288. /**
  3289. * Returns the node's type.
  3290. *
  3291. * @param {NodeBuilder} builder - The current node builder.
  3292. * @return {string} The type of the node.
  3293. */
  3294. getElementType( builder ) {
  3295. return this.getNodeType( builder );
  3296. }
  3297. /**
  3298. * This method builds the output node and returns the resulting array as a shader string.
  3299. *
  3300. * @param {NodeBuilder} builder - The current node builder.
  3301. * @return {string} The generated shader string.
  3302. */
  3303. generate( builder ) {
  3304. const type = this.getNodeType( builder );
  3305. return builder.generateArray( type, this.count, this.values );
  3306. }
  3307. }
  3308. /**
  3309. * TSL function for creating an array node.
  3310. *
  3311. * @tsl
  3312. * @function
  3313. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3314. * or an array containing the default values (e.g., [ vec3() ]).
  3315. * @param {?number} [count] - Size of the array.
  3316. * @returns {ArrayNode}
  3317. */
  3318. const array = ( ...params ) => {
  3319. let node;
  3320. if ( params.length === 1 ) {
  3321. const values = params[ 0 ];
  3322. node = new ArrayNode( null, values.length, values );
  3323. } else {
  3324. const nodeType = params[ 0 ];
  3325. const count = params[ 1 ];
  3326. node = new ArrayNode( nodeType, count );
  3327. }
  3328. return nodeObject( node );
  3329. };
  3330. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3331. /**
  3332. * These node represents an assign operation. Meaning a node is assigned
  3333. * to another node.
  3334. *
  3335. * @augments TempNode
  3336. */
  3337. class AssignNode extends TempNode {
  3338. static get type() {
  3339. return 'AssignNode';
  3340. }
  3341. /**
  3342. * Constructs a new assign node.
  3343. *
  3344. * @param {Node} targetNode - The target node.
  3345. * @param {Node} sourceNode - The source type.
  3346. */
  3347. constructor( targetNode, sourceNode ) {
  3348. super();
  3349. /**
  3350. * The target node.
  3351. *
  3352. * @type {Node}
  3353. */
  3354. this.targetNode = targetNode;
  3355. /**
  3356. * The source node.
  3357. *
  3358. * @type {Node}
  3359. */
  3360. this.sourceNode = sourceNode;
  3361. /**
  3362. * This flag can be used for type testing.
  3363. *
  3364. * @type {boolean}
  3365. * @readonly
  3366. * @default true
  3367. */
  3368. this.isAssignNode = true;
  3369. }
  3370. /**
  3371. * Whether this node is used more than once in context of other nodes. This method
  3372. * is overwritten since it always returns `false` (assigns are unique).
  3373. *
  3374. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3375. */
  3376. hasDependencies() {
  3377. return false;
  3378. }
  3379. getNodeType( builder, output ) {
  3380. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3381. }
  3382. /**
  3383. * Whether a split is required when assigning source to target. This can happen when the component length of
  3384. * target and source data type does not match.
  3385. *
  3386. * @param {NodeBuilder} builder - The current node builder.
  3387. * @return {boolean} Whether a split is required when assigning source to target.
  3388. */
  3389. needsSplitAssign( builder ) {
  3390. const { targetNode } = this;
  3391. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3392. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3393. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3394. return assignDifferentVector;
  3395. }
  3396. return false;
  3397. }
  3398. setup( builder ) {
  3399. const { targetNode, sourceNode } = this;
  3400. const targetProperties = builder.getNodeProperties( targetNode );
  3401. targetProperties.assign = true;
  3402. const properties = builder.getNodeProperties( this );
  3403. properties.sourceNode = sourceNode;
  3404. properties.targetNode = targetNode.context( { assign: true } );
  3405. }
  3406. generate( builder, output ) {
  3407. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3408. const needsSplitAssign = this.needsSplitAssign( builder );
  3409. const targetType = targetNode.getNodeType( builder );
  3410. const target = targetNode.build( builder );
  3411. const source = sourceNode.build( builder, targetType );
  3412. const sourceType = sourceNode.getNodeType( builder );
  3413. const nodeData = builder.getDataFromNode( this );
  3414. //
  3415. let snippet;
  3416. if ( nodeData.initialized === true ) {
  3417. if ( output !== 'void' ) {
  3418. snippet = target;
  3419. }
  3420. } else if ( needsSplitAssign ) {
  3421. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3422. const sourceProperty = builder.getPropertyName( sourceVar );
  3423. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3424. const splitNode = targetNode.node;
  3425. const splitTargetNode = splitNode.node.context( { assign: true } );
  3426. const targetRoot = splitTargetNode.build( builder );
  3427. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3428. const component = splitNode.components[ i ];
  3429. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3430. }
  3431. if ( output !== 'void' ) {
  3432. snippet = target;
  3433. }
  3434. } else {
  3435. snippet = `${ target } = ${ source }`;
  3436. if ( output === 'void' || sourceType === 'void' ) {
  3437. builder.addLineFlowCode( snippet, this );
  3438. if ( output !== 'void' ) {
  3439. snippet = target;
  3440. }
  3441. }
  3442. }
  3443. nodeData.initialized = true;
  3444. return builder.format( snippet, targetType, output );
  3445. }
  3446. }
  3447. /**
  3448. * TSL function for creating an assign node.
  3449. *
  3450. * @tsl
  3451. * @function
  3452. * @param {Node} targetNode - The target node.
  3453. * @param {Node} sourceNode - The source type.
  3454. * @returns {AssignNode}
  3455. */
  3456. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3457. addMethodChaining( 'assign', assign );
  3458. /**
  3459. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3460. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3461. * this logic.
  3462. *
  3463. * @augments TempNode
  3464. */
  3465. class FunctionCallNode extends TempNode {
  3466. static get type() {
  3467. return 'FunctionCallNode';
  3468. }
  3469. /**
  3470. * Constructs a new function call node.
  3471. *
  3472. * @param {?FunctionNode} functionNode - The function node.
  3473. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3474. */
  3475. constructor( functionNode = null, parameters = {} ) {
  3476. super();
  3477. /**
  3478. * The function node.
  3479. *
  3480. * @type {?FunctionNode}
  3481. * @default null
  3482. */
  3483. this.functionNode = functionNode;
  3484. /**
  3485. * The parameters of the function call.
  3486. *
  3487. * @type {Object<string, Node>}
  3488. * @default {}
  3489. */
  3490. this.parameters = parameters;
  3491. }
  3492. /**
  3493. * Sets the parameters of the function call node.
  3494. *
  3495. * @param {Object<string, Node>} parameters - The parameters to set.
  3496. * @return {FunctionCallNode} A reference to this node.
  3497. */
  3498. setParameters( parameters ) {
  3499. this.parameters = parameters;
  3500. return this;
  3501. }
  3502. /**
  3503. * Returns the parameters of the function call node.
  3504. *
  3505. * @return {Object<string, Node>} The parameters of this node.
  3506. */
  3507. getParameters() {
  3508. return this.parameters;
  3509. }
  3510. getNodeType( builder ) {
  3511. return this.functionNode.getNodeType( builder );
  3512. }
  3513. generate( builder ) {
  3514. const params = [];
  3515. const functionNode = this.functionNode;
  3516. const inputs = functionNode.getInputs( builder );
  3517. const parameters = this.parameters;
  3518. const generateInput = ( node, inputNode ) => {
  3519. const type = inputNode.type;
  3520. const pointer = type === 'pointer';
  3521. let output;
  3522. if ( pointer ) output = '&' + node.build( builder );
  3523. else output = node.build( builder, type );
  3524. return output;
  3525. };
  3526. if ( Array.isArray( parameters ) ) {
  3527. if ( parameters.length > inputs.length ) {
  3528. console.error( 'THREE.TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3529. parameters.length = inputs.length;
  3530. } else if ( parameters.length < inputs.length ) {
  3531. console.error( 'THREE.TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3532. while ( parameters.length < inputs.length ) {
  3533. parameters.push( float( 0 ) );
  3534. }
  3535. }
  3536. for ( let i = 0; i < parameters.length; i ++ ) {
  3537. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3538. }
  3539. } else {
  3540. for ( const inputNode of inputs ) {
  3541. const node = parameters[ inputNode.name ];
  3542. if ( node !== undefined ) {
  3543. params.push( generateInput( node, inputNode ) );
  3544. } else {
  3545. console.error( `THREE.TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3546. params.push( generateInput( float( 0 ), inputNode ) );
  3547. }
  3548. }
  3549. }
  3550. const functionName = functionNode.build( builder, 'property' );
  3551. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3552. }
  3553. }
  3554. const call = ( func, ...params ) => {
  3555. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3556. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3557. };
  3558. addMethodChaining( 'call', call );
  3559. const _vectorOperators = {
  3560. '==': 'equal',
  3561. '!=': 'notEqual',
  3562. '<': 'lessThan',
  3563. '>': 'greaterThan',
  3564. '<=': 'lessThanEqual',
  3565. '>=': 'greaterThanEqual',
  3566. '%': 'mod'
  3567. };
  3568. /**
  3569. * This node represents basic mathematical and logical operations like addition,
  3570. * subtraction or comparisons (e.g. `equal()`).
  3571. *
  3572. * @augments TempNode
  3573. */
  3574. class OperatorNode extends TempNode {
  3575. static get type() {
  3576. return 'OperatorNode';
  3577. }
  3578. /**
  3579. * Constructs a new operator node.
  3580. *
  3581. * @param {string} op - The operator.
  3582. * @param {Node} aNode - The first input.
  3583. * @param {Node} bNode - The second input.
  3584. * @param {...Node} params - Additional input parameters.
  3585. */
  3586. constructor( op, aNode, bNode, ...params ) {
  3587. super();
  3588. if ( params.length > 0 ) {
  3589. let finalOp = new OperatorNode( op, aNode, bNode );
  3590. for ( let i = 0; i < params.length - 1; i ++ ) {
  3591. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3592. }
  3593. aNode = finalOp;
  3594. bNode = params[ params.length - 1 ];
  3595. }
  3596. /**
  3597. * The operator.
  3598. *
  3599. * @type {string}
  3600. */
  3601. this.op = op;
  3602. /**
  3603. * The first input.
  3604. *
  3605. * @type {Node}
  3606. */
  3607. this.aNode = aNode;
  3608. /**
  3609. * The second input.
  3610. *
  3611. * @type {Node}
  3612. */
  3613. this.bNode = bNode;
  3614. /**
  3615. * This flag can be used for type testing.
  3616. *
  3617. * @type {boolean}
  3618. * @readonly
  3619. * @default true
  3620. */
  3621. this.isOperatorNode = true;
  3622. }
  3623. /**
  3624. * Returns the operator method name.
  3625. *
  3626. * @param {NodeBuilder} builder - The current node builder.
  3627. * @param {string} output - The output type.
  3628. * @returns {string} The operator method name.
  3629. */
  3630. getOperatorMethod( builder, output ) {
  3631. return builder.getMethod( _vectorOperators[ this.op ], output );
  3632. }
  3633. /**
  3634. * This method is overwritten since the node type is inferred from the operator
  3635. * and the input node types.
  3636. *
  3637. * @param {NodeBuilder} builder - The current node builder.
  3638. * @return {string} The node type.
  3639. */
  3640. getNodeType( builder ) {
  3641. const op = this.op;
  3642. const aNode = this.aNode;
  3643. const bNode = this.bNode;
  3644. const typeA = aNode.getNodeType( builder );
  3645. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3646. if ( typeA === 'void' || typeB === 'void' ) {
  3647. return 'void';
  3648. } else if ( op === '%' ) {
  3649. return typeA;
  3650. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3651. return builder.getIntegerType( typeA );
  3652. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3653. return 'bool';
  3654. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3655. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3656. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3657. } else {
  3658. // Handle matrix operations
  3659. if ( builder.isMatrix( typeA ) ) {
  3660. if ( typeB === 'float' ) {
  3661. return typeA; // matrix * scalar = matrix
  3662. } else if ( builder.isVector( typeB ) ) {
  3663. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3664. } else if ( builder.isMatrix( typeB ) ) {
  3665. return typeA; // matrix * matrix
  3666. }
  3667. } else if ( builder.isMatrix( typeB ) ) {
  3668. if ( typeA === 'float' ) {
  3669. return typeB; // scalar * matrix = matrix
  3670. } else if ( builder.isVector( typeA ) ) {
  3671. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3672. }
  3673. }
  3674. // Handle non-matrix cases
  3675. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3676. // anytype x anytype: use the greater length vector
  3677. return typeB;
  3678. }
  3679. return typeA;
  3680. }
  3681. }
  3682. generate( builder, output ) {
  3683. const op = this.op;
  3684. const { aNode, bNode } = this;
  3685. const type = this.getNodeType( builder );
  3686. let typeA = null;
  3687. let typeB = null;
  3688. if ( type !== 'void' ) {
  3689. typeA = aNode.getNodeType( builder );
  3690. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3691. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3692. if ( builder.isVector( typeA ) ) {
  3693. typeB = typeA;
  3694. } else if ( builder.isVector( typeB ) ) {
  3695. typeA = typeB;
  3696. } else if ( typeA !== typeB ) {
  3697. typeA = typeB = 'float';
  3698. }
  3699. } else if ( op === '>>' || op === '<<' ) {
  3700. typeA = type;
  3701. typeB = builder.changeComponentType( typeB, 'uint' );
  3702. } else if ( op === '%' ) {
  3703. typeA = type;
  3704. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3705. } else if ( builder.isMatrix( typeA ) ) {
  3706. if ( typeB === 'float' ) {
  3707. // Keep matrix type for typeA, but ensure typeB stays float
  3708. typeB = 'float';
  3709. } else if ( builder.isVector( typeB ) ) {
  3710. // matrix x vector
  3711. typeB = builder.getVectorFromMatrix( typeA );
  3712. } else if ( builder.isMatrix( typeB ) ) ; else {
  3713. typeA = typeB = type;
  3714. }
  3715. } else if ( builder.isMatrix( typeB ) ) {
  3716. if ( typeA === 'float' ) {
  3717. // Keep matrix type for typeB, but ensure typeA stays float
  3718. typeA = 'float';
  3719. } else if ( builder.isVector( typeA ) ) {
  3720. // vector x matrix
  3721. typeA = builder.getVectorFromMatrix( typeB );
  3722. } else {
  3723. typeA = typeB = type;
  3724. }
  3725. } else {
  3726. // anytype x anytype
  3727. typeA = typeB = type;
  3728. }
  3729. } else {
  3730. typeA = typeB = type;
  3731. }
  3732. const a = aNode.build( builder, typeA );
  3733. const b = bNode ? bNode.build( builder, typeB ) : null;
  3734. const fnOpSnippet = builder.getFunctionOperator( op );
  3735. if ( output !== 'void' ) {
  3736. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3737. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3738. if ( isGLSL ) {
  3739. if ( builder.isVector( typeA ) ) {
  3740. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3741. } else {
  3742. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3743. }
  3744. } else {
  3745. // WGSL
  3746. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3747. }
  3748. } else if ( op === '%' ) {
  3749. if ( builder.isInteger( typeB ) ) {
  3750. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3751. } else {
  3752. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3753. }
  3754. } else if ( op === '!' || op === '~' ) {
  3755. return builder.format( `(${op}${a})`, typeA, output );
  3756. } else if ( fnOpSnippet ) {
  3757. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3758. } else {
  3759. // Handle matrix operations
  3760. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3761. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3762. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3763. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3764. } else {
  3765. let snippet = `( ${ a } ${ op } ${ b } )`;
  3766. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3767. snippet = `all${ snippet }`;
  3768. }
  3769. return builder.format( snippet, type, output );
  3770. }
  3771. }
  3772. } else if ( typeA !== 'void' ) {
  3773. if ( fnOpSnippet ) {
  3774. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3775. } else {
  3776. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3777. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3778. } else {
  3779. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3780. }
  3781. }
  3782. }
  3783. }
  3784. serialize( data ) {
  3785. super.serialize( data );
  3786. data.op = this.op;
  3787. }
  3788. deserialize( data ) {
  3789. super.deserialize( data );
  3790. this.op = data.op;
  3791. }
  3792. }
  3793. /**
  3794. * Returns the addition of two or more value.
  3795. *
  3796. * @tsl
  3797. * @function
  3798. * @param {Node} a - The first input.
  3799. * @param {Node} b - The second input.
  3800. * @param {...Node} params - Additional input parameters.
  3801. * @returns {OperatorNode}
  3802. */
  3803. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3804. /**
  3805. * Returns the subtraction of two or more value.
  3806. *
  3807. * @tsl
  3808. * @function
  3809. * @param {Node} a - The first input.
  3810. * @param {Node} b - The second input.
  3811. * @param {...Node} params - Additional input parameters.
  3812. * @returns {OperatorNode}
  3813. */
  3814. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  3815. /**
  3816. * Returns the multiplication of two or more value.
  3817. *
  3818. * @tsl
  3819. * @function
  3820. * @param {Node} a - The first input.
  3821. * @param {Node} b - The second input.
  3822. * @param {...Node} params - Additional input parameters.
  3823. * @returns {OperatorNode}
  3824. */
  3825. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  3826. /**
  3827. * Returns the division of two or more value.
  3828. *
  3829. * @tsl
  3830. * @function
  3831. * @param {Node} a - The first input.
  3832. * @param {Node} b - The second input.
  3833. * @param {...Node} params - Additional input parameters.
  3834. * @returns {OperatorNode}
  3835. */
  3836. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  3837. /**
  3838. * Computes the remainder of dividing the first node by the second one.
  3839. *
  3840. * @tsl
  3841. * @function
  3842. * @param {Node} a - The first input.
  3843. * @param {Node} b - The second input.
  3844. * @returns {OperatorNode}
  3845. */
  3846. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  3847. /**
  3848. * Checks if two nodes are equal.
  3849. *
  3850. * @tsl
  3851. * @function
  3852. * @param {Node} a - The first input.
  3853. * @param {Node} b - The second input.
  3854. * @returns {OperatorNode}
  3855. */
  3856. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  3857. /**
  3858. * Checks if two nodes are not equal.
  3859. *
  3860. * @tsl
  3861. * @function
  3862. * @param {Node} a - The first input.
  3863. * @param {Node} b - The second input.
  3864. * @returns {OperatorNode}
  3865. */
  3866. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  3867. /**
  3868. * Checks if the first node is less than the second.
  3869. *
  3870. * @tsl
  3871. * @function
  3872. * @param {Node} a - The first input.
  3873. * @param {Node} b - The second input.
  3874. * @returns {OperatorNode}
  3875. */
  3876. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  3877. /**
  3878. * Checks if the first node is greater than the second.
  3879. *
  3880. * @tsl
  3881. * @function
  3882. * @param {Node} a - The first input.
  3883. * @param {Node} b - The second input.
  3884. * @returns {OperatorNode}
  3885. */
  3886. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  3887. /**
  3888. * Checks if the first node is less than or equal to the second.
  3889. *
  3890. * @tsl
  3891. * @function
  3892. * @param {Node} a - The first input.
  3893. * @param {Node} b - The second input.
  3894. * @returns {OperatorNode}
  3895. */
  3896. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  3897. /**
  3898. * Checks if the first node is greater than or equal to the second.
  3899. *
  3900. * @tsl
  3901. * @function
  3902. * @param {Node} a - The first input.
  3903. * @param {Node} b - The second input.
  3904. * @returns {OperatorNode}
  3905. */
  3906. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  3907. /**
  3908. * Performs a logical AND operation on multiple nodes.
  3909. *
  3910. * @tsl
  3911. * @function
  3912. * @param {...Node} nodes - The input nodes to be combined using AND.
  3913. * @returns {OperatorNode}
  3914. */
  3915. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  3916. /**
  3917. * Performs a logical OR operation on multiple nodes.
  3918. *
  3919. * @tsl
  3920. * @function
  3921. * @param {...Node} nodes - The input nodes to be combined using OR.
  3922. * @returns {OperatorNode}
  3923. */
  3924. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  3925. /**
  3926. * Performs logical NOT on a node.
  3927. *
  3928. * @tsl
  3929. * @function
  3930. * @param {Node} value - The value.
  3931. * @returns {OperatorNode}
  3932. */
  3933. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  3934. /**
  3935. * Performs logical XOR on two nodes.
  3936. *
  3937. * @tsl
  3938. * @function
  3939. * @param {Node} a - The first input.
  3940. * @param {Node} b - The second input.
  3941. * @returns {OperatorNode}
  3942. */
  3943. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  3944. /**
  3945. * Performs bitwise AND on two nodes.
  3946. *
  3947. * @tsl
  3948. * @function
  3949. * @param {Node} a - The first input.
  3950. * @param {Node} b - The second input.
  3951. * @returns {OperatorNode}
  3952. */
  3953. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  3954. /**
  3955. * Performs bitwise NOT on a node.
  3956. *
  3957. * @tsl
  3958. * @function
  3959. * @param {Node} a - The first input.
  3960. * @param {Node} b - The second input.
  3961. * @returns {OperatorNode}
  3962. */
  3963. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 2 ).setName( 'bitNot' );
  3964. /**
  3965. * Performs bitwise OR on two nodes.
  3966. *
  3967. * @tsl
  3968. * @function
  3969. * @param {Node} a - The first input.
  3970. * @param {Node} b - The second input.
  3971. * @returns {OperatorNode}
  3972. */
  3973. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  3974. /**
  3975. * Performs bitwise XOR on two nodes.
  3976. *
  3977. * @tsl
  3978. * @function
  3979. * @param {Node} a - The first input.
  3980. * @param {Node} b - The second input.
  3981. * @returns {OperatorNode}
  3982. */
  3983. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  3984. /**
  3985. * Shifts a node to the left.
  3986. *
  3987. * @tsl
  3988. * @function
  3989. * @param {Node} a - The node to shift.
  3990. * @param {Node} b - The value to shift.
  3991. * @returns {OperatorNode}
  3992. */
  3993. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  3994. /**
  3995. * Shifts a node to the right.
  3996. *
  3997. * @tsl
  3998. * @function
  3999. * @param {Node} a - The node to shift.
  4000. * @param {Node} b - The value to shift.
  4001. * @returns {OperatorNode}
  4002. */
  4003. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4004. /**
  4005. * Increments a node by 1.
  4006. *
  4007. * @tsl
  4008. * @function
  4009. * @param {Node} a - The node to increment.
  4010. * @returns {OperatorNode}
  4011. */
  4012. const incrementBefore = Fn( ( [ a ] ) => {
  4013. a.addAssign( 1 );
  4014. return a;
  4015. } );
  4016. /**
  4017. * Decrements a node by 1.
  4018. *
  4019. * @tsl
  4020. * @function
  4021. * @param {Node} a - The node to decrement.
  4022. * @returns {OperatorNode}
  4023. */
  4024. const decrementBefore = Fn( ( [ a ] ) => {
  4025. a.subAssign( 1 );
  4026. return a;
  4027. } );
  4028. /**
  4029. * Increments a node by 1 and returns the previous value.
  4030. *
  4031. * @tsl
  4032. * @function
  4033. * @param {Node} a - The node to increment.
  4034. * @returns {OperatorNode}
  4035. */
  4036. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4037. const temp = int( a ).toConst();
  4038. a.addAssign( 1 );
  4039. return temp;
  4040. } );
  4041. /**
  4042. * Decrements a node by 1 and returns the previous value.
  4043. *
  4044. * @tsl
  4045. * @function
  4046. * @param {Node} a - The node to decrement.
  4047. * @returns {OperatorNode}
  4048. */
  4049. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4050. const temp = int( a ).toConst();
  4051. a.subAssign( 1 );
  4052. return temp;
  4053. } );
  4054. addMethodChaining( 'add', add );
  4055. addMethodChaining( 'sub', sub );
  4056. addMethodChaining( 'mul', mul );
  4057. addMethodChaining( 'div', div );
  4058. addMethodChaining( 'mod', mod );
  4059. addMethodChaining( 'equal', equal );
  4060. addMethodChaining( 'notEqual', notEqual );
  4061. addMethodChaining( 'lessThan', lessThan );
  4062. addMethodChaining( 'greaterThan', greaterThan );
  4063. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4064. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4065. addMethodChaining( 'and', and );
  4066. addMethodChaining( 'or', or );
  4067. addMethodChaining( 'not', not );
  4068. addMethodChaining( 'xor', xor );
  4069. addMethodChaining( 'bitAnd', bitAnd );
  4070. addMethodChaining( 'bitNot', bitNot );
  4071. addMethodChaining( 'bitOr', bitOr );
  4072. addMethodChaining( 'bitXor', bitXor );
  4073. addMethodChaining( 'shiftLeft', shiftLeft );
  4074. addMethodChaining( 'shiftRight', shiftRight );
  4075. addMethodChaining( 'incrementBefore', incrementBefore );
  4076. addMethodChaining( 'decrementBefore', decrementBefore );
  4077. addMethodChaining( 'increment', increment );
  4078. addMethodChaining( 'decrement', decrement );
  4079. /**
  4080. * @tsl
  4081. * @function
  4082. * @deprecated since r175. Use {@link mod} instead.
  4083. *
  4084. * @param {Node} a - The first input.
  4085. * @param {Node} b - The second input.
  4086. * @returns {OperatorNode}
  4087. */
  4088. const modInt = ( a, b ) => { // @deprecated, r175
  4089. console.warn( 'THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4090. return mod( int( a ), int( b ) );
  4091. };
  4092. addMethodChaining( 'modInt', modInt );
  4093. /**
  4094. * This node represents a variety of mathematical methods available in shaders.
  4095. * They are divided into three categories:
  4096. *
  4097. * - Methods with one input like `sin`, `cos` or `normalize`.
  4098. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4099. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4100. *
  4101. * @augments TempNode
  4102. */
  4103. class MathNode extends TempNode {
  4104. static get type() {
  4105. return 'MathNode';
  4106. }
  4107. /**
  4108. * Constructs a new math node.
  4109. *
  4110. * @param {string} method - The method name.
  4111. * @param {Node} aNode - The first input.
  4112. * @param {?Node} [bNode=null] - The second input.
  4113. * @param {?Node} [cNode=null] - The third input.
  4114. */
  4115. constructor( method, aNode, bNode = null, cNode = null ) {
  4116. super();
  4117. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4118. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4119. let finalOp = new MathNode( method, aNode, bNode );
  4120. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4121. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4122. }
  4123. aNode = finalOp;
  4124. bNode = arguments[ arguments.length - 1 ];
  4125. cNode = null;
  4126. }
  4127. /**
  4128. * The method name.
  4129. *
  4130. * @type {string}
  4131. */
  4132. this.method = method;
  4133. /**
  4134. * The first input.
  4135. *
  4136. * @type {Node}
  4137. */
  4138. this.aNode = aNode;
  4139. /**
  4140. * The second input.
  4141. *
  4142. * @type {?Node}
  4143. * @default null
  4144. */
  4145. this.bNode = bNode;
  4146. /**
  4147. * The third input.
  4148. *
  4149. * @type {?Node}
  4150. * @default null
  4151. */
  4152. this.cNode = cNode;
  4153. /**
  4154. * This flag can be used for type testing.
  4155. *
  4156. * @type {boolean}
  4157. * @readonly
  4158. * @default true
  4159. */
  4160. this.isMathNode = true;
  4161. }
  4162. /**
  4163. * The input type is inferred from the node types of the input nodes.
  4164. *
  4165. * @param {NodeBuilder} builder - The current node builder.
  4166. * @return {string} The input type.
  4167. */
  4168. getInputType( builder ) {
  4169. const aType = this.aNode.getNodeType( builder );
  4170. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4171. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4172. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4173. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4174. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4175. if ( aLen > bLen && aLen > cLen ) {
  4176. return aType;
  4177. } else if ( bLen > cLen ) {
  4178. return bType;
  4179. } else if ( cLen > aLen ) {
  4180. return cType;
  4181. }
  4182. return aType;
  4183. }
  4184. /**
  4185. * The selected method as well as the input type determine the node type of this node.
  4186. *
  4187. * @param {NodeBuilder} builder - The current node builder.
  4188. * @return {string} The node type.
  4189. */
  4190. getNodeType( builder ) {
  4191. const method = this.method;
  4192. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4193. return 'float';
  4194. } else if ( method === MathNode.CROSS ) {
  4195. return 'vec3';
  4196. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4197. return 'bool';
  4198. } else if ( method === MathNode.EQUALS ) {
  4199. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4200. } else {
  4201. return this.getInputType( builder );
  4202. }
  4203. }
  4204. setup( builder ) {
  4205. const { aNode, bNode, method } = this;
  4206. let outputNode = null;
  4207. if ( method === MathNode.ONE_MINUS ) {
  4208. outputNode = sub( 1.0, aNode );
  4209. } else if ( method === MathNode.RECIPROCAL ) {
  4210. outputNode = div( 1.0, aNode );
  4211. } else if ( method === MathNode.DIFFERENCE ) {
  4212. outputNode = abs( sub( aNode, bNode ) );
  4213. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4214. // dir can be either a direction vector or a normal vector
  4215. // upper-left 3x3 of matrix is assumed to be orthogonal
  4216. let tA = aNode;
  4217. let tB = bNode;
  4218. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4219. tB = vec4( vec3( tB ), 0.0 );
  4220. } else {
  4221. tA = vec4( vec3( tA ), 0.0 );
  4222. }
  4223. const mulNode = mul( tA, tB ).xyz;
  4224. outputNode = normalize( mulNode );
  4225. }
  4226. if ( outputNode !== null ) {
  4227. return outputNode;
  4228. } else {
  4229. return super.setup( builder );
  4230. }
  4231. }
  4232. generate( builder, output ) {
  4233. const properties = builder.getNodeProperties( this );
  4234. if ( properties.outputNode ) {
  4235. return super.generate( builder, output );
  4236. }
  4237. let method = this.method;
  4238. const type = this.getNodeType( builder );
  4239. const inputType = this.getInputType( builder );
  4240. const a = this.aNode;
  4241. const b = this.bNode;
  4242. const c = this.cNode;
  4243. const coordinateSystem = builder.renderer.coordinateSystem;
  4244. if ( method === MathNode.NEGATE ) {
  4245. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4246. } else {
  4247. const params = [];
  4248. if ( method === MathNode.CROSS ) {
  4249. params.push(
  4250. a.build( builder, type ),
  4251. b.build( builder, type )
  4252. );
  4253. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4254. params.push(
  4255. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4256. b.build( builder, inputType )
  4257. );
  4258. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4259. params.push(
  4260. a.build( builder, inputType ),
  4261. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4262. );
  4263. } else if ( method === MathNode.REFRACT ) {
  4264. params.push(
  4265. a.build( builder, inputType ),
  4266. b.build( builder, inputType ),
  4267. c.build( builder, 'float' )
  4268. );
  4269. } else if ( method === MathNode.MIX ) {
  4270. params.push(
  4271. a.build( builder, inputType ),
  4272. b.build( builder, inputType ),
  4273. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4274. );
  4275. } else {
  4276. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4277. method = 'atan2';
  4278. }
  4279. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4280. console.warn( `THREE.TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4281. method = '/*' + method + '*/';
  4282. }
  4283. params.push( a.build( builder, inputType ) );
  4284. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4285. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4286. }
  4287. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4288. }
  4289. }
  4290. serialize( data ) {
  4291. super.serialize( data );
  4292. data.method = this.method;
  4293. }
  4294. deserialize( data ) {
  4295. super.deserialize( data );
  4296. this.method = data.method;
  4297. }
  4298. }
  4299. // 1 input
  4300. MathNode.ALL = 'all';
  4301. MathNode.ANY = 'any';
  4302. MathNode.RADIANS = 'radians';
  4303. MathNode.DEGREES = 'degrees';
  4304. MathNode.EXP = 'exp';
  4305. MathNode.EXP2 = 'exp2';
  4306. MathNode.LOG = 'log';
  4307. MathNode.LOG2 = 'log2';
  4308. MathNode.SQRT = 'sqrt';
  4309. MathNode.INVERSE_SQRT = 'inversesqrt';
  4310. MathNode.FLOOR = 'floor';
  4311. MathNode.CEIL = 'ceil';
  4312. MathNode.NORMALIZE = 'normalize';
  4313. MathNode.FRACT = 'fract';
  4314. MathNode.SIN = 'sin';
  4315. MathNode.COS = 'cos';
  4316. MathNode.TAN = 'tan';
  4317. MathNode.ASIN = 'asin';
  4318. MathNode.ACOS = 'acos';
  4319. MathNode.ATAN = 'atan';
  4320. MathNode.ABS = 'abs';
  4321. MathNode.SIGN = 'sign';
  4322. MathNode.LENGTH = 'length';
  4323. MathNode.NEGATE = 'negate';
  4324. MathNode.ONE_MINUS = 'oneMinus';
  4325. MathNode.DFDX = 'dFdx';
  4326. MathNode.DFDY = 'dFdy';
  4327. MathNode.ROUND = 'round';
  4328. MathNode.RECIPROCAL = 'reciprocal';
  4329. MathNode.TRUNC = 'trunc';
  4330. MathNode.FWIDTH = 'fwidth';
  4331. MathNode.TRANSPOSE = 'transpose';
  4332. MathNode.DETERMINANT = 'determinant';
  4333. MathNode.INVERSE = 'inverse';
  4334. // 2 inputs
  4335. MathNode.BITCAST = 'bitcast';
  4336. MathNode.EQUALS = 'equals';
  4337. MathNode.MIN = 'min';
  4338. MathNode.MAX = 'max';
  4339. MathNode.STEP = 'step';
  4340. MathNode.REFLECT = 'reflect';
  4341. MathNode.DISTANCE = 'distance';
  4342. MathNode.DIFFERENCE = 'difference';
  4343. MathNode.DOT = 'dot';
  4344. MathNode.CROSS = 'cross';
  4345. MathNode.POW = 'pow';
  4346. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4347. // 3 inputs
  4348. MathNode.MIX = 'mix';
  4349. MathNode.CLAMP = 'clamp';
  4350. MathNode.REFRACT = 'refract';
  4351. MathNode.SMOOTHSTEP = 'smoothstep';
  4352. MathNode.FACEFORWARD = 'faceforward';
  4353. // 1 inputs
  4354. /**
  4355. * A small value used to handle floating-point precision errors.
  4356. *
  4357. * @tsl
  4358. * @type {Node<float>}
  4359. */
  4360. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4361. /**
  4362. * Represents infinity.
  4363. *
  4364. * @tsl
  4365. * @type {Node<float>}
  4366. */
  4367. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4368. /**
  4369. * Represents PI.
  4370. *
  4371. * @tsl
  4372. * @type {Node<float>}
  4373. */
  4374. const PI = /*@__PURE__*/ float( Math.PI );
  4375. /**
  4376. * Represents PI * 2.
  4377. *
  4378. * @tsl
  4379. * @type {Node<float>}
  4380. */
  4381. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  4382. /**
  4383. * Returns `true` if all components of `x` are `true`.
  4384. *
  4385. * @tsl
  4386. * @function
  4387. * @param {Node | number} x - The parameter.
  4388. * @returns {Node<bool>}
  4389. */
  4390. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4391. /**
  4392. * Returns `true` if any components of `x` are `true`.
  4393. *
  4394. * @tsl
  4395. * @function
  4396. * @param {Node | number} x - The parameter.
  4397. * @returns {Node<bool>}
  4398. */
  4399. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4400. /**
  4401. * Converts a quantity in degrees to radians.
  4402. *
  4403. * @tsl
  4404. * @function
  4405. * @param {Node | number} x - The input in degrees.
  4406. * @returns {Node}
  4407. */
  4408. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4409. /**
  4410. * Convert a quantity in radians to degrees.
  4411. *
  4412. * @tsl
  4413. * @function
  4414. * @param {Node | number} x - The input in radians.
  4415. * @returns {Node}
  4416. */
  4417. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4418. /**
  4419. * Returns the natural exponentiation of the parameter.
  4420. *
  4421. * @tsl
  4422. * @function
  4423. * @param {Node | number} x - The parameter.
  4424. * @returns {Node}
  4425. */
  4426. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4427. /**
  4428. * Returns 2 raised to the power of the parameter.
  4429. *
  4430. * @tsl
  4431. * @function
  4432. * @param {Node | number} x - The parameter.
  4433. * @returns {Node}
  4434. */
  4435. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4436. /**
  4437. * Returns the natural logarithm of the parameter.
  4438. *
  4439. * @tsl
  4440. * @function
  4441. * @param {Node | number} x - The parameter.
  4442. * @returns {Node}
  4443. */
  4444. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4445. /**
  4446. * Returns the base 2 logarithm of the parameter.
  4447. *
  4448. * @tsl
  4449. * @function
  4450. * @param {Node | number} x - The parameter.
  4451. * @returns {Node}
  4452. */
  4453. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4454. /**
  4455. * Returns the square root of the parameter.
  4456. *
  4457. * @tsl
  4458. * @function
  4459. * @param {Node | number} x - The parameter.
  4460. * @returns {Node}
  4461. */
  4462. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4463. /**
  4464. * Returns the inverse of the square root of the parameter.
  4465. *
  4466. * @tsl
  4467. * @function
  4468. * @param {Node | number} x - The parameter.
  4469. * @returns {Node}
  4470. */
  4471. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4472. /**
  4473. * Finds the nearest integer less than or equal to the parameter.
  4474. *
  4475. * @tsl
  4476. * @function
  4477. * @param {Node | number} x - The parameter.
  4478. * @returns {Node}
  4479. */
  4480. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4481. /**
  4482. * Finds the nearest integer that is greater than or equal to the parameter.
  4483. *
  4484. * @tsl
  4485. * @function
  4486. * @param {Node | number} x - The parameter.
  4487. * @returns {Node}
  4488. */
  4489. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4490. /**
  4491. * Calculates the unit vector in the same direction as the original vector.
  4492. *
  4493. * @tsl
  4494. * @function
  4495. * @param {Node} x - The input vector.
  4496. * @returns {Node}
  4497. */
  4498. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4499. /**
  4500. * Computes the fractional part of the parameter.
  4501. *
  4502. * @tsl
  4503. * @function
  4504. * @param {Node | number} x - The parameter.
  4505. * @returns {Node}
  4506. */
  4507. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4508. /**
  4509. * Returns the sine of the parameter.
  4510. *
  4511. * @tsl
  4512. * @function
  4513. * @param {Node | number} x - The parameter.
  4514. * @returns {Node}
  4515. */
  4516. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4517. /**
  4518. * Returns the cosine of the parameter.
  4519. *
  4520. * @tsl
  4521. * @function
  4522. * @param {Node | number} x - The parameter.
  4523. * @returns {Node}
  4524. */
  4525. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4526. /**
  4527. * Returns the tangent of the parameter.
  4528. *
  4529. * @tsl
  4530. * @function
  4531. * @param {Node | number} x - The parameter.
  4532. * @returns {Node}
  4533. */
  4534. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4535. /**
  4536. * Returns the arcsine of the parameter.
  4537. *
  4538. * @tsl
  4539. * @function
  4540. * @param {Node | number} x - The parameter.
  4541. * @returns {Node}
  4542. */
  4543. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4544. /**
  4545. * Returns the arccosine of the parameter.
  4546. *
  4547. * @tsl
  4548. * @function
  4549. * @param {Node | number} x - The parameter.
  4550. * @returns {Node}
  4551. */
  4552. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4553. /**
  4554. * Returns the arc-tangent of the parameter.
  4555. * If two parameters are provided, the result is `atan2(y/x)`.
  4556. *
  4557. * @tsl
  4558. * @function
  4559. * @param {Node | number} y - The y parameter.
  4560. * @param {?(Node | number)} x - The x parameter.
  4561. * @returns {Node}
  4562. */
  4563. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4564. /**
  4565. * Returns the absolute value of the parameter.
  4566. *
  4567. * @tsl
  4568. * @function
  4569. * @param {Node | number} x - The parameter.
  4570. * @returns {Node}
  4571. */
  4572. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4573. /**
  4574. * Extracts the sign of the parameter.
  4575. *
  4576. * @tsl
  4577. * @function
  4578. * @param {Node | number} x - The parameter.
  4579. * @returns {Node}
  4580. */
  4581. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4582. /**
  4583. * Calculates the length of a vector.
  4584. *
  4585. * @tsl
  4586. * @function
  4587. * @param {Node} x - The parameter.
  4588. * @returns {Node<float>}
  4589. */
  4590. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4591. /**
  4592. * Negates the value of the parameter (-x).
  4593. *
  4594. * @tsl
  4595. * @function
  4596. * @param {Node | number} x - The parameter.
  4597. * @returns {Node}
  4598. */
  4599. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4600. /**
  4601. * Return `1` minus the parameter.
  4602. *
  4603. * @tsl
  4604. * @function
  4605. * @param {Node | number} x - The parameter.
  4606. * @returns {Node}
  4607. */
  4608. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4609. /**
  4610. * Returns the partial derivative of the parameter with respect to x.
  4611. *
  4612. * @tsl
  4613. * @function
  4614. * @param {Node | number} x - The parameter.
  4615. * @returns {Node}
  4616. */
  4617. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4618. /**
  4619. * Returns the partial derivative of the parameter with respect to y.
  4620. *
  4621. * @tsl
  4622. * @function
  4623. * @param {Node | number} x - The parameter.
  4624. * @returns {Node}
  4625. */
  4626. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4627. /**
  4628. * Rounds the parameter to the nearest integer.
  4629. *
  4630. * @tsl
  4631. * @function
  4632. * @param {Node | number} x - The parameter.
  4633. * @returns {Node}
  4634. */
  4635. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4636. /**
  4637. * Returns the reciprocal of the parameter `(1/x)`.
  4638. *
  4639. * @tsl
  4640. * @function
  4641. * @param {Node | number} x - The parameter.
  4642. * @returns {Node}
  4643. */
  4644. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4645. /**
  4646. * Truncates the parameter, removing the fractional part.
  4647. *
  4648. * @tsl
  4649. * @function
  4650. * @param {Node | number} x - The parameter.
  4651. * @returns {Node}
  4652. */
  4653. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4654. /**
  4655. * Returns the sum of the absolute derivatives in x and y.
  4656. *
  4657. * @tsl
  4658. * @function
  4659. * @param {Node | number} x - The parameter.
  4660. * @returns {Node}
  4661. */
  4662. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4663. /**
  4664. * Returns the transpose of a matrix.
  4665. *
  4666. * @tsl
  4667. * @function
  4668. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4669. * @returns {Node}
  4670. */
  4671. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4672. /**
  4673. * Returns the determinant of a matrix.
  4674. *
  4675. * @tsl
  4676. * @function
  4677. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4678. * @returns {Node<float>}
  4679. */
  4680. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4681. /**
  4682. * Returns the inverse of a matrix.
  4683. *
  4684. * @tsl
  4685. * @function
  4686. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4687. * @returns {Node<mat2|mat3|mat4>}
  4688. */
  4689. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4690. // 2 inputs
  4691. /**
  4692. * Reinterpret the bit representation of a value in one type as a value in another type.
  4693. *
  4694. * @tsl
  4695. * @function
  4696. * @param {Node | number} x - The parameter.
  4697. * @param {string} y - The new type.
  4698. * @returns {Node}
  4699. */
  4700. const bitcast = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.BITCAST ).setParameterLength( 2 );
  4701. /**
  4702. * Returns `true` if `x` equals `y`.
  4703. *
  4704. * @tsl
  4705. * @function
  4706. * @param {Node | number} x - The first parameter.
  4707. * @param {Node | number} y - The second parameter.
  4708. * @deprecated since r175. Use {@link equal} instead.
  4709. * @returns {Node<bool>}
  4710. */
  4711. const equals = ( x, y ) => { // @deprecated, r172
  4712. console.warn( 'THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4713. return equal( x, y );
  4714. };
  4715. /**
  4716. * Returns the least of the given values.
  4717. *
  4718. * @tsl
  4719. * @function
  4720. * @param {...(Node | number)} values - The values to compare.
  4721. * @returns {Node}
  4722. */
  4723. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4724. /**
  4725. * Returns the greatest of the given values.
  4726. *
  4727. * @tsl
  4728. * @function
  4729. * @param {...(Node | number)} values - The values to compare.
  4730. * @returns {Node}
  4731. */
  4732. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4733. /**
  4734. * Generate a step function by comparing two values.
  4735. *
  4736. * @tsl
  4737. * @function
  4738. * @param {Node | number} x - The y parameter.
  4739. * @param {Node | number} y - The x parameter.
  4740. * @returns {Node}
  4741. */
  4742. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4743. /**
  4744. * Calculates the reflection direction for an incident vector.
  4745. *
  4746. * @tsl
  4747. * @function
  4748. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4749. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4750. * @returns {Node<vec2|vec3|vec4>}
  4751. */
  4752. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4753. /**
  4754. * Calculates the distance between two points.
  4755. *
  4756. * @tsl
  4757. * @function
  4758. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4759. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4760. * @returns {Node<float>}
  4761. */
  4762. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4763. /**
  4764. * Calculates the absolute difference between two values.
  4765. *
  4766. * @tsl
  4767. * @function
  4768. * @param {Node | number} x - The first parameter.
  4769. * @param {Node | number} y - The second parameter.
  4770. * @returns {Node}
  4771. */
  4772. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4773. /**
  4774. * Calculates the dot product of two vectors.
  4775. *
  4776. * @tsl
  4777. * @function
  4778. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4779. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4780. * @returns {Node<float>}
  4781. */
  4782. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4783. /**
  4784. * Calculates the cross product of two vectors.
  4785. *
  4786. * @tsl
  4787. * @function
  4788. * @param {Node<vec2|vec3>} x - The first vector.
  4789. * @param {Node<vec2|vec3>} y - The second vector.
  4790. * @returns {Node<float|vec3>}
  4791. */
  4792. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4793. /**
  4794. * Return the value of the first parameter raised to the power of the second one.
  4795. *
  4796. * @tsl
  4797. * @function
  4798. * @param {Node | number} x - The first parameter.
  4799. * @param {Node | number} y - The second parameter.
  4800. * @returns {Node}
  4801. */
  4802. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  4803. /**
  4804. * Returns the square of the parameter.
  4805. *
  4806. * @tsl
  4807. * @function
  4808. * @param {Node | number} x - The first parameter.
  4809. * @returns {Node}
  4810. */
  4811. const pow2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 2 ).setParameterLength( 1 );
  4812. /**
  4813. * Returns the cube of the parameter.
  4814. *
  4815. * @tsl
  4816. * @function
  4817. * @param {Node | number} x - The first parameter.
  4818. * @returns {Node}
  4819. */
  4820. const pow3 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 3 ).setParameterLength( 1 );
  4821. /**
  4822. * Returns the fourth power of the parameter.
  4823. *
  4824. * @tsl
  4825. * @function
  4826. * @param {Node | number} x - The first parameter.
  4827. * @returns {Node}
  4828. */
  4829. const pow4 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 4 ).setParameterLength( 1 );
  4830. /**
  4831. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4832. *
  4833. * @tsl
  4834. * @function
  4835. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4836. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4837. * @returns {Node}
  4838. */
  4839. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  4840. /**
  4841. * Returns the cube root of a number.
  4842. *
  4843. * @tsl
  4844. * @function
  4845. * @param {Node | number} a - The first parameter.
  4846. * @returns {Node}
  4847. */
  4848. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4849. /**
  4850. * Calculate the squared length of a vector.
  4851. *
  4852. * @tsl
  4853. * @function
  4854. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4855. * @returns {Node<float>}
  4856. */
  4857. const lengthSq = ( a ) => dot( a, a );
  4858. /**
  4859. * Linearly interpolates between two values.
  4860. *
  4861. * @tsl
  4862. * @function
  4863. * @param {Node | number} a - The first parameter.
  4864. * @param {Node | number} b - The second parameter.
  4865. * @param {Node | number} t - The interpolation value.
  4866. * @returns {Node}
  4867. */
  4868. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  4869. /**
  4870. * Constrains a value to lie between two further values.
  4871. *
  4872. * @tsl
  4873. * @function
  4874. * @param {Node | number} value - The value to constrain.
  4875. * @param {Node | number} [low=0] - The lower bound.
  4876. * @param {Node | number} [high=1] - The upper bound.
  4877. * @returns {Node}
  4878. */
  4879. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4880. /**
  4881. * Constrains a value between `0` and `1`.
  4882. *
  4883. * @tsl
  4884. * @function
  4885. * @param {Node | number} value - The value to constrain.
  4886. * @returns {Node}
  4887. */
  4888. const saturate = ( value ) => clamp( value );
  4889. /**
  4890. * Calculates the refraction direction for an incident vector.
  4891. *
  4892. * @tsl
  4893. * @function
  4894. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4895. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4896. * @param {Node<float>} eta - The ratio of indices of refraction.
  4897. * @returns {Node<vec2|vec3|vec4>}
  4898. */
  4899. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  4900. /**
  4901. * Performs a Hermite interpolation between two values.
  4902. *
  4903. * @tsl
  4904. * @function
  4905. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4906. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4907. * @param {Node | number} x - The source value for interpolation.
  4908. * @returns {Node}
  4909. */
  4910. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  4911. /**
  4912. * Returns a vector pointing in the same direction as another.
  4913. *
  4914. * @tsl
  4915. * @function
  4916. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4917. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4918. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4919. * @returns {Node<vec2|vec3|vec4>}
  4920. */
  4921. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  4922. /**
  4923. * Returns a random value for the given uv.
  4924. *
  4925. * @tsl
  4926. * @function
  4927. * @param {Node<vec2>} uv - The uv node.
  4928. * @returns {Node<float>}
  4929. */
  4930. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4931. const a = 12.9898, b = 78.233, c = 43758.5453;
  4932. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4933. return fract( sin( sn ).mul( c ) );
  4934. } );
  4935. /**
  4936. * Alias for `mix()` with a different parameter order.
  4937. *
  4938. * @tsl
  4939. * @function
  4940. * @param {Node | number} t - The interpolation value.
  4941. * @param {Node | number} e1 - The first parameter.
  4942. * @param {Node | number} e2 - The second parameter.
  4943. * @returns {Node}
  4944. */
  4945. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4946. /**
  4947. * Alias for `smoothstep()` with a different parameter order.
  4948. *
  4949. * @tsl
  4950. * @function
  4951. * @param {Node | number} x - The source value for interpolation.
  4952. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4953. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4954. * @returns {Node}
  4955. */
  4956. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4957. /**
  4958. * Alias for `step()` with a different parameter order.
  4959. *
  4960. * @tsl
  4961. * @function
  4962. * @param {Node | number} x - The source value for interpolation.
  4963. * @param {Node | number} edge - The edge value.
  4964. * @returns {Node}
  4965. */
  4966. const stepElement = ( x, edge ) => step( edge, x );
  4967. /**
  4968. * Returns the arc-tangent of the quotient of its parameters.
  4969. *
  4970. * @tsl
  4971. * @function
  4972. * @deprecated since r172. Use {@link atan} instead.
  4973. *
  4974. * @param {Node | number} y - The y parameter.
  4975. * @param {Node | number} x - The x parameter.
  4976. * @returns {Node}
  4977. */
  4978. const atan2 = ( y, x ) => { // @deprecated, r172
  4979. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4980. return atan( y, x );
  4981. };
  4982. // GLSL alias function
  4983. const faceforward = faceForward;
  4984. const inversesqrt = inverseSqrt;
  4985. // Method chaining
  4986. addMethodChaining( 'all', all );
  4987. addMethodChaining( 'any', any );
  4988. addMethodChaining( 'equals', equals );
  4989. addMethodChaining( 'radians', radians );
  4990. addMethodChaining( 'degrees', degrees );
  4991. addMethodChaining( 'exp', exp );
  4992. addMethodChaining( 'exp2', exp2 );
  4993. addMethodChaining( 'log', log );
  4994. addMethodChaining( 'log2', log2 );
  4995. addMethodChaining( 'sqrt', sqrt );
  4996. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4997. addMethodChaining( 'floor', floor );
  4998. addMethodChaining( 'ceil', ceil );
  4999. addMethodChaining( 'normalize', normalize );
  5000. addMethodChaining( 'fract', fract );
  5001. addMethodChaining( 'sin', sin );
  5002. addMethodChaining( 'cos', cos );
  5003. addMethodChaining( 'tan', tan );
  5004. addMethodChaining( 'asin', asin );
  5005. addMethodChaining( 'acos', acos );
  5006. addMethodChaining( 'atan', atan );
  5007. addMethodChaining( 'abs', abs );
  5008. addMethodChaining( 'sign', sign );
  5009. addMethodChaining( 'length', length );
  5010. addMethodChaining( 'lengthSq', lengthSq );
  5011. addMethodChaining( 'negate', negate );
  5012. addMethodChaining( 'oneMinus', oneMinus );
  5013. addMethodChaining( 'dFdx', dFdx );
  5014. addMethodChaining( 'dFdy', dFdy );
  5015. addMethodChaining( 'round', round );
  5016. addMethodChaining( 'reciprocal', reciprocal );
  5017. addMethodChaining( 'trunc', trunc );
  5018. addMethodChaining( 'fwidth', fwidth );
  5019. addMethodChaining( 'atan2', atan2 );
  5020. addMethodChaining( 'min', min$1 );
  5021. addMethodChaining( 'max', max$1 );
  5022. addMethodChaining( 'step', stepElement );
  5023. addMethodChaining( 'reflect', reflect );
  5024. addMethodChaining( 'distance', distance );
  5025. addMethodChaining( 'dot', dot );
  5026. addMethodChaining( 'cross', cross );
  5027. addMethodChaining( 'pow', pow );
  5028. addMethodChaining( 'pow2', pow2 );
  5029. addMethodChaining( 'pow3', pow3 );
  5030. addMethodChaining( 'pow4', pow4 );
  5031. addMethodChaining( 'transformDirection', transformDirection );
  5032. addMethodChaining( 'mix', mixElement );
  5033. addMethodChaining( 'clamp', clamp );
  5034. addMethodChaining( 'refract', refract );
  5035. addMethodChaining( 'smoothstep', smoothstepElement );
  5036. addMethodChaining( 'faceForward', faceForward );
  5037. addMethodChaining( 'difference', difference );
  5038. addMethodChaining( 'saturate', saturate );
  5039. addMethodChaining( 'cbrt', cbrt );
  5040. addMethodChaining( 'transpose', transpose );
  5041. addMethodChaining( 'determinant', determinant );
  5042. addMethodChaining( 'inverse', inverse );
  5043. addMethodChaining( 'rand', rand );
  5044. /**
  5045. * Represents a logical `if/else` statement. Can be used as an alternative
  5046. * to the `If()`/`Else()` syntax.
  5047. *
  5048. * The corresponding TSL `select()` looks like so:
  5049. * ```js
  5050. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5051. * ```
  5052. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5053. * determine the outcome of the entire statement.
  5054. *
  5055. * @augments Node
  5056. */
  5057. class ConditionalNode extends Node {
  5058. static get type() {
  5059. return 'ConditionalNode';
  5060. }
  5061. /**
  5062. * Constructs a new conditional node.
  5063. *
  5064. * @param {Node} condNode - The node that defines the condition.
  5065. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5066. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5067. */
  5068. constructor( condNode, ifNode, elseNode = null ) {
  5069. super();
  5070. /**
  5071. * The node that defines the condition.
  5072. *
  5073. * @type {Node}
  5074. */
  5075. this.condNode = condNode;
  5076. /**
  5077. * The node that is evaluate when the condition ends up `true`.
  5078. *
  5079. * @type {Node}
  5080. */
  5081. this.ifNode = ifNode;
  5082. /**
  5083. * The node that is evaluate when the condition ends up `false`.
  5084. *
  5085. * @type {?Node}
  5086. * @default null
  5087. */
  5088. this.elseNode = elseNode;
  5089. }
  5090. /**
  5091. * This method is overwritten since the node type is inferred from the if/else
  5092. * nodes.
  5093. *
  5094. * @param {NodeBuilder} builder - The current node builder.
  5095. * @return {string} The node type.
  5096. */
  5097. getNodeType( builder ) {
  5098. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5099. if ( ifNode === undefined ) {
  5100. // fallback setup
  5101. builder.flowBuildStage( this, 'setup' );
  5102. return this.getNodeType( builder );
  5103. }
  5104. const ifType = ifNode.getNodeType( builder );
  5105. if ( elseNode !== null ) {
  5106. const elseType = elseNode.getNodeType( builder );
  5107. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5108. return elseType;
  5109. }
  5110. }
  5111. return ifType;
  5112. }
  5113. setup( builder ) {
  5114. const condNode = this.condNode.cache();
  5115. const ifNode = this.ifNode.cache();
  5116. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  5117. //
  5118. const currentNodeBlock = builder.context.nodeBlock;
  5119. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5120. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5121. //
  5122. const properties = builder.getNodeProperties( this );
  5123. properties.condNode = condNode;
  5124. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  5125. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  5126. }
  5127. generate( builder, output ) {
  5128. const type = this.getNodeType( builder );
  5129. const nodeData = builder.getDataFromNode( this );
  5130. if ( nodeData.nodeProperty !== undefined ) {
  5131. return nodeData.nodeProperty;
  5132. }
  5133. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5134. const functionNode = builder.currentFunctionNode;
  5135. const needsOutput = output !== 'void';
  5136. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5137. nodeData.nodeProperty = nodeProperty;
  5138. const nodeSnippet = condNode.build( builder, 'bool' );
  5139. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5140. let ifSnippet = ifNode.build( builder, type );
  5141. if ( ifSnippet ) {
  5142. if ( needsOutput ) {
  5143. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5144. } else {
  5145. ifSnippet = 'return ' + ifSnippet + ';';
  5146. if ( functionNode === null ) {
  5147. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5148. ifSnippet = '// ' + ifSnippet;
  5149. }
  5150. }
  5151. }
  5152. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5153. if ( elseNode !== null ) {
  5154. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5155. let elseSnippet = elseNode.build( builder, type );
  5156. if ( elseSnippet ) {
  5157. if ( needsOutput ) {
  5158. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5159. } else {
  5160. elseSnippet = 'return ' + elseSnippet + ';';
  5161. if ( functionNode === null ) {
  5162. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5163. elseSnippet = '// ' + elseSnippet;
  5164. }
  5165. }
  5166. }
  5167. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5168. } else {
  5169. builder.addFlowCode( '\n\n' );
  5170. }
  5171. return builder.format( nodeProperty, type, output );
  5172. }
  5173. }
  5174. /**
  5175. * TSL function for creating a conditional node.
  5176. *
  5177. * @tsl
  5178. * @function
  5179. * @param {Node} condNode - The node that defines the condition.
  5180. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5181. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5182. * @returns {ConditionalNode}
  5183. */
  5184. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5185. addMethodChaining( 'select', select );
  5186. /**
  5187. * This node can be used as a context management component for another node.
  5188. * {@link NodeBuilder} performs its node building process in a specific context and
  5189. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5190. *
  5191. * ```js
  5192. *node.context( { getUV: () => customCoord } );
  5193. *```
  5194. * @augments Node
  5195. */
  5196. class ContextNode extends Node {
  5197. static get type() {
  5198. return 'ContextNode';
  5199. }
  5200. /**
  5201. * Constructs a new context node.
  5202. *
  5203. * @param {Node} node - The node whose context should be modified.
  5204. * @param {Object} [value={}] - The modified context data.
  5205. */
  5206. constructor( node, value = {} ) {
  5207. super();
  5208. /**
  5209. * This flag can be used for type testing.
  5210. *
  5211. * @type {boolean}
  5212. * @readonly
  5213. * @default true
  5214. */
  5215. this.isContextNode = true;
  5216. /**
  5217. * The node whose context should be modified.
  5218. *
  5219. * @type {Node}
  5220. */
  5221. this.node = node;
  5222. /**
  5223. * The modified context data.
  5224. *
  5225. * @type {Object}
  5226. * @default {}
  5227. */
  5228. this.value = value;
  5229. }
  5230. /**
  5231. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5232. *
  5233. * @return {Node} A reference to {@link ContextNode#node}.
  5234. */
  5235. getScope() {
  5236. return this.node.getScope();
  5237. }
  5238. /**
  5239. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5240. *
  5241. * @param {NodeBuilder} builder - The current node builder.
  5242. * @return {string} The node type.
  5243. */
  5244. getNodeType( builder ) {
  5245. return this.node.getNodeType( builder );
  5246. }
  5247. analyze( builder ) {
  5248. const previousContext = builder.getContext();
  5249. builder.setContext( { ...builder.context, ...this.value } );
  5250. this.node.build( builder );
  5251. builder.setContext( previousContext );
  5252. }
  5253. setup( builder ) {
  5254. const previousContext = builder.getContext();
  5255. builder.setContext( { ...builder.context, ...this.value } );
  5256. this.node.build( builder );
  5257. builder.setContext( previousContext );
  5258. }
  5259. generate( builder, output ) {
  5260. const previousContext = builder.getContext();
  5261. builder.setContext( { ...builder.context, ...this.value } );
  5262. const snippet = this.node.build( builder, output );
  5263. builder.setContext( previousContext );
  5264. return snippet;
  5265. }
  5266. }
  5267. /**
  5268. * TSL function for creating a context node.
  5269. *
  5270. * @tsl
  5271. * @function
  5272. * @param {Node} node - The node whose context should be modified.
  5273. * @param {Object} [value={}] - The modified context data.
  5274. * @returns {ContextNode}
  5275. */
  5276. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5277. /**
  5278. * TSL function for defining a label context value for a given node.
  5279. *
  5280. * @tsl
  5281. * @function
  5282. * @param {Node} node - The node whose context should be modified.
  5283. * @param {string} name - The name/label to set.
  5284. * @returns {ContextNode}
  5285. */
  5286. const label = ( node, name ) => context( node, { label: name } );
  5287. addMethodChaining( 'context', context );
  5288. addMethodChaining( 'label', label );
  5289. /**
  5290. * Class for representing shader variables as nodes. Variables are created from
  5291. * existing nodes like the following:
  5292. *
  5293. * ```js
  5294. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5295. * ```
  5296. *
  5297. * @augments Node
  5298. */
  5299. class VarNode extends Node {
  5300. static get type() {
  5301. return 'VarNode';
  5302. }
  5303. /**
  5304. * Constructs a new variable node.
  5305. *
  5306. * @param {Node} node - The node for which a variable should be created.
  5307. * @param {?string} [name=null] - The name of the variable in the shader.
  5308. * @param {boolean} [readOnly=false] - The read-only flag.
  5309. */
  5310. constructor( node, name = null, readOnly = false ) {
  5311. super();
  5312. /**
  5313. * The node for which a variable should be created.
  5314. *
  5315. * @type {Node}
  5316. */
  5317. this.node = node;
  5318. /**
  5319. * The name of the variable in the shader. If no name is defined,
  5320. * the node system auto-generates one.
  5321. *
  5322. * @type {?string}
  5323. * @default null
  5324. */
  5325. this.name = name;
  5326. /**
  5327. * `VarNode` sets this property to `true` by default.
  5328. *
  5329. * @type {boolean}
  5330. * @default true
  5331. */
  5332. this.global = true;
  5333. /**
  5334. * This flag can be used for type testing.
  5335. *
  5336. * @type {boolean}
  5337. * @readonly
  5338. * @default true
  5339. */
  5340. this.isVarNode = true;
  5341. /**
  5342. *
  5343. * The read-only flag.
  5344. *
  5345. * @type {boolean}
  5346. * @default false
  5347. */
  5348. this.readOnly = readOnly;
  5349. /**
  5350. *
  5351. * Add this flag to the node system to indicate that this node require parents.
  5352. *
  5353. * @type {boolean}
  5354. * @default true
  5355. */
  5356. this.parents = true;
  5357. /**
  5358. * This flag is used to indicate that this node is used for intent.
  5359. *
  5360. * @type {boolean}
  5361. * @default false
  5362. */
  5363. this.intent = false;
  5364. }
  5365. /**
  5366. * Sets the intent flag for this node.
  5367. *
  5368. * This flag is used to indicate that this node is used for intent
  5369. * and should not be built directly. Instead, it is used to indicate that
  5370. * the node should be treated as a variable intent.
  5371. *
  5372. * It's useful for assigning variables without needing creating a new variable node.
  5373. *
  5374. * @param {boolean} value - The value to set for the intent flag.
  5375. * @returns {VarNode} This node.
  5376. */
  5377. setIntent( value ) {
  5378. this.intent = value;
  5379. return this;
  5380. }
  5381. /**
  5382. * Returns the intent flag of this node.
  5383. *
  5384. * @return {boolean} The intent flag.
  5385. */
  5386. getIntent() {
  5387. return this.intent;
  5388. }
  5389. getMemberType( builder, name ) {
  5390. return this.node.getMemberType( builder, name );
  5391. }
  5392. getElementType( builder ) {
  5393. return this.node.getElementType( builder );
  5394. }
  5395. getNodeType( builder ) {
  5396. return this.node.getNodeType( builder );
  5397. }
  5398. getArrayCount( builder ) {
  5399. return this.node.getArrayCount( builder );
  5400. }
  5401. build( ...params ) {
  5402. if ( this.intent === true ) {
  5403. const builder = params[ 0 ];
  5404. const properties = builder.getNodeProperties( this );
  5405. if ( properties.assign !== true ) {
  5406. return this.node.build( ...params );
  5407. }
  5408. }
  5409. return super.build( ...params );
  5410. }
  5411. generate( builder ) {
  5412. const { node, name, readOnly } = this;
  5413. const { renderer } = builder;
  5414. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5415. let isDeterministic = false;
  5416. let shouldTreatAsReadOnly = false;
  5417. if ( readOnly ) {
  5418. isDeterministic = builder.isDeterministic( node );
  5419. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5420. }
  5421. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5422. const snippet = node.build( builder, vectorType );
  5423. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5424. const propertyName = builder.getPropertyName( nodeVar );
  5425. let declarationPrefix = propertyName;
  5426. if ( shouldTreatAsReadOnly ) {
  5427. if ( isWebGPUBackend ) {
  5428. declarationPrefix = isDeterministic
  5429. ? `const ${ propertyName }`
  5430. : `let ${ propertyName }`;
  5431. } else {
  5432. const count = node.getArrayCount( builder );
  5433. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5434. }
  5435. }
  5436. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5437. return propertyName;
  5438. }
  5439. }
  5440. /**
  5441. * TSL function for creating a var node.
  5442. *
  5443. * @tsl
  5444. * @function
  5445. * @param {Node} node - The node for which a variable should be created.
  5446. * @param {?string} name - The name of the variable in the shader.
  5447. * @returns {VarNode}
  5448. */
  5449. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5450. /**
  5451. * TSL function for creating a var node.
  5452. *
  5453. * @tsl
  5454. * @function
  5455. * @param {Node} node - The node for which a variable should be created.
  5456. * @param {?string} name - The name of the variable in the shader.
  5457. * @returns {VarNode}
  5458. */
  5459. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5460. /**
  5461. * TSL function for creating a const node.
  5462. *
  5463. * @tsl
  5464. * @function
  5465. * @param {Node} node - The node for which a constant should be created.
  5466. * @param {?string} name - The name of the constant in the shader.
  5467. * @returns {VarNode}
  5468. */
  5469. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5470. //
  5471. //
  5472. /**
  5473. * TSL function for creating a var intent node.
  5474. *
  5475. * @tsl
  5476. * @function
  5477. * @param {Node} node - The node for which a variable should be created.
  5478. * @param {?string} name - The name of the variable in the shader.
  5479. * @returns {VarNode}
  5480. */
  5481. const VarIntent = ( node ) => {
  5482. if ( getCurrentStack() === null ) {
  5483. return node;
  5484. }
  5485. return createVar( node ).setIntent( true ).toStack();
  5486. };
  5487. // Method chaining
  5488. addMethodChaining( 'toVar', Var );
  5489. addMethodChaining( 'toConst', Const );
  5490. addMethodChaining( 'toVarIntent', VarIntent );
  5491. // Deprecated
  5492. /**
  5493. * @tsl
  5494. * @function
  5495. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  5496. *
  5497. * @param {any} node
  5498. * @returns {VarNode}
  5499. */
  5500. const temp = ( node ) => { // @deprecated, r170
  5501. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  5502. return createVar( node );
  5503. };
  5504. addMethodChaining( 'temp', temp );
  5505. /**
  5506. * This node is used to build a sub-build in the node system.
  5507. *
  5508. * @augments Node
  5509. * @param {Node} node - The node to be built in the sub-build.
  5510. * @param {string} name - The name of the sub-build.
  5511. * @param {string|null} [nodeType=null] - The type of the node, if known.
  5512. */
  5513. class SubBuildNode extends Node {
  5514. static get type() {
  5515. return 'SubBuild';
  5516. }
  5517. constructor( node, name, nodeType = null ) {
  5518. super( nodeType );
  5519. /**
  5520. * The node to be built in the sub-build.
  5521. *
  5522. * @type {Node}
  5523. */
  5524. this.node = node;
  5525. /**
  5526. * The name of the sub-build.
  5527. *
  5528. * @type {string}
  5529. */
  5530. this.name = name;
  5531. /**
  5532. * This flag can be used for type testing.
  5533. *
  5534. * @type {boolean}
  5535. * @readonly
  5536. * @default true
  5537. */
  5538. this.isSubBuildNode = true;
  5539. }
  5540. getNodeType( builder ) {
  5541. if ( this.nodeType !== null ) return this.nodeType;
  5542. builder.addSubBuild( this.name );
  5543. const nodeType = this.node.getNodeType( builder );
  5544. builder.removeSubBuild();
  5545. return nodeType;
  5546. }
  5547. build( builder, ...params ) {
  5548. builder.addSubBuild( this.name );
  5549. const data = this.node.build( builder, ...params );
  5550. builder.removeSubBuild();
  5551. return data;
  5552. }
  5553. }
  5554. /**
  5555. * Creates a new sub-build node.
  5556. *
  5557. * @tsl
  5558. * @function
  5559. * @param {Node} node - The node to be built in the sub-build.
  5560. * @param {string} name - The name of the sub-build.
  5561. * @param {string|null} [type=null] - The type of the node, if known.
  5562. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5563. */
  5564. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5565. /**
  5566. * Class for representing shader varyings as nodes. Varyings are create from
  5567. * existing nodes like the following:
  5568. *
  5569. * ```js
  5570. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5571. * ```
  5572. *
  5573. * @augments Node
  5574. */
  5575. class VaryingNode extends Node {
  5576. static get type() {
  5577. return 'VaryingNode';
  5578. }
  5579. /**
  5580. * Constructs a new varying node.
  5581. *
  5582. * @param {Node} node - The node for which a varying should be created.
  5583. * @param {?string} name - The name of the varying in the shader.
  5584. */
  5585. constructor( node, name = null ) {
  5586. super();
  5587. /**
  5588. * The node for which a varying should be created.
  5589. *
  5590. * @type {Node}
  5591. */
  5592. this.node = node;
  5593. /**
  5594. * The name of the varying in the shader. If no name is defined,
  5595. * the node system auto-generates one.
  5596. *
  5597. * @type {?string}
  5598. * @default null
  5599. */
  5600. this.name = name;
  5601. /**
  5602. * This flag can be used for type testing.
  5603. *
  5604. * @type {boolean}
  5605. * @readonly
  5606. * @default true
  5607. */
  5608. this.isVaryingNode = true;
  5609. /**
  5610. * The interpolation type of the varying data.
  5611. *
  5612. * @type {?string}
  5613. * @default null
  5614. */
  5615. this.interpolationType = null;
  5616. /**
  5617. * The interpolation sampling type of varying data.
  5618. *
  5619. * @type {?string}
  5620. * @default null
  5621. */
  5622. this.interpolationSampling = null;
  5623. /**
  5624. * This flag is used for global cache.
  5625. *
  5626. * @type {boolean}
  5627. * @default true
  5628. */
  5629. this.global = true;
  5630. }
  5631. /**
  5632. * Defines the interpolation type of the varying.
  5633. *
  5634. * @param {string} type - The interpolation type.
  5635. * @param {?string} sampling - The interpolation sampling type
  5636. * @return {VaryingNode} A reference to this node.
  5637. */
  5638. setInterpolation( type, sampling = null ) {
  5639. this.interpolationType = type;
  5640. this.interpolationSampling = sampling;
  5641. return this;
  5642. }
  5643. getHash( builder ) {
  5644. return this.name || super.getHash( builder );
  5645. }
  5646. getNodeType( builder ) {
  5647. // VaryingNode is auto type
  5648. return this.node.getNodeType( builder );
  5649. }
  5650. /**
  5651. * This method performs the setup of a varying node with the current node builder.
  5652. *
  5653. * @param {NodeBuilder} builder - The current node builder.
  5654. * @return {NodeVarying} The node varying from the node builder.
  5655. */
  5656. setupVarying( builder ) {
  5657. const properties = builder.getNodeProperties( this );
  5658. let varying = properties.varying;
  5659. if ( varying === undefined ) {
  5660. const name = this.name;
  5661. const type = this.getNodeType( builder );
  5662. const interpolationType = this.interpolationType;
  5663. const interpolationSampling = this.interpolationSampling;
  5664. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5665. properties.node = subBuild( this.node, 'VERTEX' );
  5666. }
  5667. // this property can be used to check if the varying can be optimized for a variable
  5668. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5669. return varying;
  5670. }
  5671. setup( builder ) {
  5672. this.setupVarying( builder );
  5673. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5674. }
  5675. analyze( builder ) {
  5676. this.setupVarying( builder );
  5677. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5678. }
  5679. generate( builder ) {
  5680. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5681. const properties = builder.getNodeProperties( this );
  5682. const varying = this.setupVarying( builder );
  5683. if ( properties[ propertyKey ] === undefined ) {
  5684. const type = this.getNodeType( builder );
  5685. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5686. // force node run in vertex stage
  5687. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5688. properties[ propertyKey ] = propertyName;
  5689. }
  5690. return builder.getPropertyName( varying );
  5691. }
  5692. }
  5693. /**
  5694. * TSL function for creating a varying node.
  5695. *
  5696. * @tsl
  5697. * @function
  5698. * @param {Node} node - The node for which a varying should be created.
  5699. * @param {?string} name - The name of the varying in the shader.
  5700. * @returns {VaryingNode}
  5701. */
  5702. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5703. /**
  5704. * Computes a node in the vertex stage.
  5705. *
  5706. * @tsl
  5707. * @function
  5708. * @param {Node} node - The node which should be executed in the vertex stage.
  5709. * @returns {VaryingNode}
  5710. */
  5711. const vertexStage = ( node ) => varying( node );
  5712. addMethodChaining( 'toVarying', varying );
  5713. addMethodChaining( 'toVertexStage', vertexStage );
  5714. // Deprecated
  5715. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5716. console.warn( 'THREE.TSL: .varying() has been renamed to .toVarying().' );
  5717. return varying( ...params );
  5718. } );
  5719. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5720. console.warn( 'THREE.TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5721. return varying( ...params );
  5722. } );
  5723. /**
  5724. * Converts the given color value from sRGB to linear-sRGB color space.
  5725. *
  5726. * @tsl
  5727. * @function
  5728. * @param {Node<vec3>} color - The sRGB color.
  5729. * @return {Node<vec3>} The linear-sRGB color.
  5730. */
  5731. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5732. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5733. const b = color.mul( 0.0773993808 );
  5734. const factor = color.lessThanEqual( 0.04045 );
  5735. const rgbResult = mix( a, b, factor );
  5736. return rgbResult;
  5737. } ).setLayout( {
  5738. name: 'sRGBTransferEOTF',
  5739. type: 'vec3',
  5740. inputs: [
  5741. { name: 'color', type: 'vec3' }
  5742. ]
  5743. } );
  5744. /**
  5745. * Converts the given color value from linear-sRGB to sRGB color space.
  5746. *
  5747. * @tsl
  5748. * @function
  5749. * @param {Node<vec3>} color - The linear-sRGB color.
  5750. * @return {Node<vec3>} The sRGB color.
  5751. */
  5752. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5753. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5754. const b = color.mul( 12.92 );
  5755. const factor = color.lessThanEqual( 0.0031308 );
  5756. const rgbResult = mix( a, b, factor );
  5757. return rgbResult;
  5758. } ).setLayout( {
  5759. name: 'sRGBTransferOETF',
  5760. type: 'vec3',
  5761. inputs: [
  5762. { name: 'color', type: 'vec3' }
  5763. ]
  5764. } );
  5765. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5766. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5767. /**
  5768. * This node represents a color space conversion. Meaning it converts
  5769. * a color value from a source to a target color space.
  5770. *
  5771. * @augments TempNode
  5772. */
  5773. class ColorSpaceNode extends TempNode {
  5774. static get type() {
  5775. return 'ColorSpaceNode';
  5776. }
  5777. /**
  5778. * Constructs a new color space node.
  5779. *
  5780. * @param {Node} colorNode - Represents the color to convert.
  5781. * @param {string} source - The source color space.
  5782. * @param {string} target - The target color space.
  5783. */
  5784. constructor( colorNode, source, target ) {
  5785. super( 'vec4' );
  5786. /**
  5787. * Represents the color to convert.
  5788. *
  5789. * @type {Node}
  5790. */
  5791. this.colorNode = colorNode;
  5792. /**
  5793. * The source color space.
  5794. *
  5795. * @type {string}
  5796. */
  5797. this.source = source;
  5798. /**
  5799. * The target color space.
  5800. *
  5801. * @type {string}
  5802. */
  5803. this.target = target;
  5804. }
  5805. /**
  5806. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5807. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5808. * color management and renderer.
  5809. *
  5810. * @param {NodeBuilder} builder - The current node builder.
  5811. * @param {string} colorSpace - The color space to resolve.
  5812. * @return {string} The resolved color space.
  5813. */
  5814. resolveColorSpace( builder, colorSpace ) {
  5815. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5816. return ColorManagement.workingColorSpace;
  5817. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5818. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5819. }
  5820. return colorSpace;
  5821. }
  5822. setup( builder ) {
  5823. const { colorNode } = this;
  5824. const source = this.resolveColorSpace( builder, this.source );
  5825. const target = this.resolveColorSpace( builder, this.target );
  5826. let outputNode = colorNode;
  5827. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5828. return outputNode;
  5829. }
  5830. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5831. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5832. }
  5833. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5834. outputNode = vec4(
  5835. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5836. outputNode.a
  5837. );
  5838. }
  5839. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5840. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5841. }
  5842. return outputNode;
  5843. }
  5844. }
  5845. /**
  5846. * TSL function for converting a given color node from the current working color space to the given color space.
  5847. *
  5848. * @tsl
  5849. * @function
  5850. * @param {Node} node - Represents the node to convert.
  5851. * @param {string} targetColorSpace - The target color space.
  5852. * @returns {ColorSpaceNode}
  5853. */
  5854. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  5855. /**
  5856. * TSL function for converting a given color node from the given color space to the current working color space.
  5857. *
  5858. * @tsl
  5859. * @function
  5860. * @param {Node} node - Represents the node to convert.
  5861. * @param {string} sourceColorSpace - The source color space.
  5862. * @returns {ColorSpaceNode}
  5863. */
  5864. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  5865. /**
  5866. * TSL function for converting a given color node from one color space to another one.
  5867. *
  5868. * @tsl
  5869. * @function
  5870. * @param {Node} node - Represents the node to convert.
  5871. * @param {string} sourceColorSpace - The source color space.
  5872. * @param {string} targetColorSpace - The target color space.
  5873. * @returns {ColorSpaceNode}
  5874. */
  5875. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5876. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5877. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5878. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5879. /**
  5880. * This class is only relevant if the referenced property is array-like.
  5881. * In this case, `ReferenceElementNode` allows to refer to a specific
  5882. * element inside the data structure via an index.
  5883. *
  5884. * @augments ArrayElementNode
  5885. */
  5886. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5887. static get type() {
  5888. return 'ReferenceElementNode';
  5889. }
  5890. /**
  5891. * Constructs a new reference element node.
  5892. *
  5893. * @param {ReferenceBaseNode} referenceNode - The reference node.
  5894. * @param {Node} indexNode - The index node that defines the element access.
  5895. */
  5896. constructor( referenceNode, indexNode ) {
  5897. super( referenceNode, indexNode );
  5898. /**
  5899. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5900. * property references to the current node.
  5901. *
  5902. * @type {?ReferenceBaseNode}
  5903. * @default null
  5904. */
  5905. this.referenceNode = referenceNode;
  5906. /**
  5907. * This flag can be used for type testing.
  5908. *
  5909. * @type {boolean}
  5910. * @readonly
  5911. * @default true
  5912. */
  5913. this.isReferenceElementNode = true;
  5914. }
  5915. /**
  5916. * This method is overwritten since the node type is inferred from
  5917. * the uniform type of the reference node.
  5918. *
  5919. * @return {string} The node type.
  5920. */
  5921. getNodeType() {
  5922. return this.referenceNode.uniformType;
  5923. }
  5924. generate( builder ) {
  5925. const snippet = super.generate( builder );
  5926. const arrayType = this.referenceNode.getNodeType();
  5927. const elementType = this.getNodeType();
  5928. return builder.format( snippet, arrayType, elementType );
  5929. }
  5930. };
  5931. /**
  5932. * Base class for nodes which establishes a reference to a property of another object.
  5933. * In this way, the value of the node is automatically linked to the value of
  5934. * referenced object. Reference nodes internally represent the linked value
  5935. * as a uniform.
  5936. *
  5937. * @augments Node
  5938. */
  5939. class ReferenceBaseNode extends Node {
  5940. static get type() {
  5941. return 'ReferenceBaseNode';
  5942. }
  5943. /**
  5944. * Constructs a new reference base node.
  5945. *
  5946. * @param {string} property - The name of the property the node refers to.
  5947. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  5948. * @param {?Object} [object=null] - The object the property belongs to.
  5949. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5950. */
  5951. constructor( property, uniformType, object = null, count = null ) {
  5952. super();
  5953. /**
  5954. * The name of the property the node refers to.
  5955. *
  5956. * @type {string}
  5957. */
  5958. this.property = property;
  5959. /**
  5960. * The uniform type that should be used to represent the property value.
  5961. *
  5962. * @type {string}
  5963. */
  5964. this.uniformType = uniformType;
  5965. /**
  5966. * The object the property belongs to.
  5967. *
  5968. * @type {?Object}
  5969. * @default null
  5970. */
  5971. this.object = object;
  5972. /**
  5973. * When the linked property is an array, this parameter defines its length.
  5974. *
  5975. * @type {?number}
  5976. * @default null
  5977. */
  5978. this.count = count;
  5979. /**
  5980. * The property name might have dots so nested properties can be referred.
  5981. * The hierarchy of the names is stored inside this array.
  5982. *
  5983. * @type {Array<string>}
  5984. */
  5985. this.properties = property.split( '.' );
  5986. /**
  5987. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  5988. * since the final reference might be updated from calling code.
  5989. *
  5990. * @type {?Object}
  5991. * @default null
  5992. */
  5993. this.reference = object;
  5994. /**
  5995. * The uniform node that holds the value of the reference node.
  5996. *
  5997. * @type {UniformNode}
  5998. * @default null
  5999. */
  6000. this.node = null;
  6001. /**
  6002. * The uniform group of the internal uniform.
  6003. *
  6004. * @type {UniformGroupNode}
  6005. * @default null
  6006. */
  6007. this.group = null;
  6008. /**
  6009. * Overwritten since reference nodes are updated per object.
  6010. *
  6011. * @type {string}
  6012. * @default 'object'
  6013. */
  6014. this.updateType = NodeUpdateType.OBJECT;
  6015. }
  6016. /**
  6017. * Sets the uniform group for this reference node.
  6018. *
  6019. * @param {UniformGroupNode} group - The uniform group to set.
  6020. * @return {ReferenceBaseNode} A reference to this node.
  6021. */
  6022. setGroup( group ) {
  6023. this.group = group;
  6024. return this;
  6025. }
  6026. /**
  6027. * When the referred property is array-like, this method can be used
  6028. * to access elements via an index node.
  6029. *
  6030. * @param {IndexNode} indexNode - indexNode.
  6031. * @return {ReferenceElementNode} A reference to an element.
  6032. */
  6033. element( indexNode ) {
  6034. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6035. }
  6036. /**
  6037. * Sets the node type which automatically defines the internal
  6038. * uniform type.
  6039. *
  6040. * @param {string} uniformType - The type to set.
  6041. */
  6042. setNodeType( uniformType ) {
  6043. const node = uniform( null, uniformType ).getSelf();
  6044. if ( this.group !== null ) {
  6045. node.setGroup( this.group );
  6046. }
  6047. this.node = node;
  6048. }
  6049. /**
  6050. * This method is overwritten since the node type is inferred from
  6051. * the type of the reference node.
  6052. *
  6053. * @param {NodeBuilder} builder - The current node builder.
  6054. * @return {string} The node type.
  6055. */
  6056. getNodeType( builder ) {
  6057. if ( this.node === null ) {
  6058. this.updateReference( builder );
  6059. this.updateValue();
  6060. }
  6061. return this.node.getNodeType( builder );
  6062. }
  6063. /**
  6064. * Returns the property value from the given referred object.
  6065. *
  6066. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6067. * @return {any} The value.
  6068. */
  6069. getValueFromReference( object = this.reference ) {
  6070. const { properties } = this;
  6071. let value = object[ properties[ 0 ] ];
  6072. for ( let i = 1; i < properties.length; i ++ ) {
  6073. value = value[ properties[ i ] ];
  6074. }
  6075. return value;
  6076. }
  6077. /**
  6078. * Allows to update the reference based on the given state. The state is only
  6079. * evaluated {@link ReferenceBaseNode#object} is not set.
  6080. *
  6081. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6082. * @return {Object} The updated reference.
  6083. */
  6084. updateReference( state ) {
  6085. this.reference = this.object !== null ? this.object : state.object;
  6086. return this.reference;
  6087. }
  6088. /**
  6089. * The output of the reference node is the internal uniform node.
  6090. *
  6091. * @return {UniformNode} The output node.
  6092. */
  6093. setup() {
  6094. this.updateValue();
  6095. return this.node;
  6096. }
  6097. /**
  6098. * Overwritten to update the internal uniform value.
  6099. *
  6100. * @param {NodeFrame} frame - A reference to the current node frame.
  6101. */
  6102. update( /*frame*/ ) {
  6103. this.updateValue();
  6104. }
  6105. /**
  6106. * Retrieves the value from the referred object property and uses it
  6107. * to updated the internal uniform.
  6108. */
  6109. updateValue() {
  6110. if ( this.node === null ) this.setNodeType( this.uniformType );
  6111. const value = this.getValueFromReference();
  6112. if ( Array.isArray( value ) ) {
  6113. this.node.array = value;
  6114. } else {
  6115. this.node.value = value;
  6116. }
  6117. }
  6118. }
  6119. /**
  6120. * TSL function for creating a reference base node.
  6121. *
  6122. * @tsl
  6123. * @function
  6124. * @param {string} name - The name of the property the node refers to.
  6125. * @param {string} type - The uniform type that should be used to represent the property value.
  6126. * @param {Object} object - The object the property belongs to.
  6127. * @returns {ReferenceBaseNode}
  6128. */
  6129. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6130. /**
  6131. * This node is a special type of reference node which is intended
  6132. * for linking renderer properties with node values.
  6133. * ```js
  6134. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6135. * ```
  6136. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6137. * automatically be updated.
  6138. *
  6139. * @augments ReferenceBaseNode
  6140. */
  6141. class RendererReferenceNode extends ReferenceBaseNode {
  6142. static get type() {
  6143. return 'RendererReferenceNode';
  6144. }
  6145. /**
  6146. * Constructs a new renderer reference node.
  6147. *
  6148. * @param {string} property - The name of the property the node refers to.
  6149. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6150. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6151. * the node refers to the renderer of the current state.
  6152. */
  6153. constructor( property, inputType, renderer = null ) {
  6154. super( property, inputType, renderer );
  6155. /**
  6156. * The renderer the property belongs to. When no renderer is set,
  6157. * the node refers to the renderer of the current state.
  6158. *
  6159. * @type {?Renderer}
  6160. * @default null
  6161. */
  6162. this.renderer = renderer;
  6163. this.setGroup( renderGroup );
  6164. }
  6165. /**
  6166. * Updates the reference based on the given state. The state is only evaluated
  6167. * {@link RendererReferenceNode#renderer} is not set.
  6168. *
  6169. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6170. * @return {Object} The updated reference.
  6171. */
  6172. updateReference( state ) {
  6173. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6174. return this.reference;
  6175. }
  6176. }
  6177. /**
  6178. * TSL function for creating a renderer reference node.
  6179. *
  6180. * @tsl
  6181. * @function
  6182. * @param {string} name - The name of the property the node refers to.
  6183. * @param {string} type - The uniform type that should be used to represent the property value.
  6184. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6185. * the node refers to the renderer of the current state.
  6186. * @returns {RendererReferenceNode}
  6187. */
  6188. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6189. /**
  6190. * This node represents a tone mapping operation.
  6191. *
  6192. * @augments TempNode
  6193. */
  6194. class ToneMappingNode extends TempNode {
  6195. static get type() {
  6196. return 'ToneMappingNode';
  6197. }
  6198. /**
  6199. * Constructs a new tone mapping node.
  6200. *
  6201. * @param {number} toneMapping - The tone mapping type.
  6202. * @param {Node} exposureNode - The tone mapping exposure.
  6203. * @param {Node} [colorNode=null] - The color node to process.
  6204. */
  6205. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6206. super( 'vec3' );
  6207. /**
  6208. * The tone mapping type.
  6209. *
  6210. * @type {number}
  6211. */
  6212. this.toneMapping = toneMapping;
  6213. /**
  6214. * The tone mapping exposure.
  6215. *
  6216. * @type {Node}
  6217. * @default null
  6218. */
  6219. this.exposureNode = exposureNode;
  6220. /**
  6221. * Represents the color to process.
  6222. *
  6223. * @type {?Node}
  6224. * @default null
  6225. */
  6226. this.colorNode = colorNode;
  6227. }
  6228. /**
  6229. * Overwrites the default `customCacheKey()` implementation by including the tone
  6230. * mapping type into the cache key.
  6231. *
  6232. * @return {number} The hash.
  6233. */
  6234. customCacheKey() {
  6235. return hash$1( this.toneMapping );
  6236. }
  6237. setup( builder ) {
  6238. const colorNode = this.colorNode || builder.context.color;
  6239. const toneMapping = this.toneMapping;
  6240. if ( toneMapping === NoToneMapping ) return colorNode;
  6241. let outputNode = null;
  6242. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6243. if ( toneMappingFn !== null ) {
  6244. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6245. } else {
  6246. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6247. outputNode = colorNode;
  6248. }
  6249. return outputNode;
  6250. }
  6251. }
  6252. /**
  6253. * TSL function for creating a tone mapping node.
  6254. *
  6255. * @tsl
  6256. * @function
  6257. * @param {number} mapping - The tone mapping type.
  6258. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6259. * @param {Node<vec3> | Color} color - The color node to process.
  6260. * @returns {ToneMappingNode<vec3>}
  6261. */
  6262. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6263. /**
  6264. * TSL object that represents the global tone mapping exposure of the renderer.
  6265. *
  6266. * @tsl
  6267. * @type {RendererReferenceNode<vec3>}
  6268. */
  6269. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6270. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6271. /**
  6272. * In earlier `three.js` versions it was only possible to define attribute data
  6273. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6274. * on the node level.
  6275. * ```js
  6276. * const geometry = new THREE.PlaneGeometry();
  6277. * const positionAttribute = geometry.getAttribute( 'position' );
  6278. *
  6279. * const colors = [];
  6280. * for ( let i = 0; i < position.count; i ++ ) {
  6281. * colors.push( 1, 0, 0 );
  6282. * }
  6283. *
  6284. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6285. * ```
  6286. * This new approach is especially interesting when geometry data are generated via
  6287. * compute shaders. The below line converts a storage buffer into an attribute node.
  6288. * ```js
  6289. * material.positionNode = positionBuffer.toAttribute();
  6290. * ```
  6291. * @augments InputNode
  6292. */
  6293. class BufferAttributeNode extends InputNode {
  6294. static get type() {
  6295. return 'BufferAttributeNode';
  6296. }
  6297. /**
  6298. * Constructs a new buffer attribute node.
  6299. *
  6300. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6301. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6302. * @param {number} [bufferStride=0] - The buffer stride.
  6303. * @param {number} [bufferOffset=0] - The buffer offset.
  6304. */
  6305. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6306. super( value, bufferType );
  6307. /**
  6308. * This flag can be used for type testing.
  6309. *
  6310. * @type {boolean}
  6311. * @readonly
  6312. * @default true
  6313. */
  6314. this.isBufferNode = true;
  6315. /**
  6316. * The buffer type (e.g. `'vec3'`).
  6317. *
  6318. * @type {?string}
  6319. * @default null
  6320. */
  6321. this.bufferType = bufferType;
  6322. /**
  6323. * The buffer stride.
  6324. *
  6325. * @type {number}
  6326. * @default 0
  6327. */
  6328. this.bufferStride = bufferStride;
  6329. /**
  6330. * The buffer offset.
  6331. *
  6332. * @type {number}
  6333. * @default 0
  6334. */
  6335. this.bufferOffset = bufferOffset;
  6336. /**
  6337. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6338. * if you are planning to update the attribute data per frame.
  6339. *
  6340. * @type {number}
  6341. * @default StaticDrawUsage
  6342. */
  6343. this.usage = StaticDrawUsage;
  6344. /**
  6345. * Whether the attribute is instanced or not.
  6346. *
  6347. * @type {boolean}
  6348. * @default false
  6349. */
  6350. this.instanced = false;
  6351. /**
  6352. * A reference to the buffer attribute.
  6353. *
  6354. * @type {?BufferAttribute}
  6355. * @default null
  6356. */
  6357. this.attribute = null;
  6358. /**
  6359. * `BufferAttributeNode` sets this property to `true` by default.
  6360. *
  6361. * @type {boolean}
  6362. * @default true
  6363. */
  6364. this.global = true;
  6365. if ( value && value.isBufferAttribute === true ) {
  6366. this.attribute = value;
  6367. this.usage = value.usage;
  6368. this.instanced = value.isInstancedBufferAttribute;
  6369. }
  6370. }
  6371. /**
  6372. * This method is overwritten since the attribute data might be shared
  6373. * and thus the hash should be shared as well.
  6374. *
  6375. * @param {NodeBuilder} builder - The current node builder.
  6376. * @return {string} The hash.
  6377. */
  6378. getHash( builder ) {
  6379. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6380. let bufferData = builder.globalCache.getData( this.value );
  6381. if ( bufferData === undefined ) {
  6382. bufferData = {
  6383. node: this
  6384. };
  6385. builder.globalCache.setData( this.value, bufferData );
  6386. }
  6387. return bufferData.node.uuid;
  6388. }
  6389. return this.uuid;
  6390. }
  6391. /**
  6392. * This method is overwritten since the node type is inferred from
  6393. * the buffer attribute.
  6394. *
  6395. * @param {NodeBuilder} builder - The current node builder.
  6396. * @return {string} The node type.
  6397. */
  6398. getNodeType( builder ) {
  6399. if ( this.bufferType === null ) {
  6400. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6401. }
  6402. return this.bufferType;
  6403. }
  6404. /**
  6405. * Depending on which value was passed to the node, `setup()` behaves
  6406. * differently. If no instance of `BufferAttribute` was passed, the method
  6407. * creates an internal attribute and configures it respectively.
  6408. *
  6409. * @param {NodeBuilder} builder - The current node builder.
  6410. */
  6411. setup( builder ) {
  6412. if ( this.attribute !== null ) return;
  6413. const type = this.getNodeType( builder );
  6414. const array = this.value;
  6415. const itemSize = builder.getTypeLength( type );
  6416. const stride = this.bufferStride || itemSize;
  6417. const offset = this.bufferOffset;
  6418. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6419. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6420. buffer.setUsage( this.usage );
  6421. this.attribute = bufferAttribute;
  6422. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6423. }
  6424. /**
  6425. * Generates the code snippet of the buffer attribute node.
  6426. *
  6427. * @param {NodeBuilder} builder - The current node builder.
  6428. * @return {string} The generated code snippet.
  6429. */
  6430. generate( builder ) {
  6431. const nodeType = this.getNodeType( builder );
  6432. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6433. const propertyName = builder.getPropertyName( nodeAttribute );
  6434. let output = null;
  6435. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6436. this.name = propertyName;
  6437. output = propertyName;
  6438. } else {
  6439. const nodeVarying = varying( this );
  6440. output = nodeVarying.build( builder, nodeType );
  6441. }
  6442. return output;
  6443. }
  6444. /**
  6445. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6446. *
  6447. * @param {NodeBuilder} builder - The current node builder.
  6448. * @return {string} The input type.
  6449. */
  6450. getInputType( /*builder*/ ) {
  6451. return 'bufferAttribute';
  6452. }
  6453. /**
  6454. * Sets the `usage` property to the given value.
  6455. *
  6456. * @param {number} value - The usage to set.
  6457. * @return {BufferAttributeNode} A reference to this node.
  6458. */
  6459. setUsage( value ) {
  6460. this.usage = value;
  6461. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6462. this.attribute.usage = value;
  6463. }
  6464. return this;
  6465. }
  6466. /**
  6467. * Sets the `instanced` property to the given value.
  6468. *
  6469. * @param {boolean} value - The value to set.
  6470. * @return {BufferAttributeNode} A reference to this node.
  6471. */
  6472. setInstanced( value ) {
  6473. this.instanced = value;
  6474. return this;
  6475. }
  6476. }
  6477. /**
  6478. * TSL function for creating a buffer attribute node.
  6479. *
  6480. * @tsl
  6481. * @function
  6482. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6483. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6484. * @param {number} [stride=0] - The buffer stride.
  6485. * @param {number} [offset=0] - The buffer offset.
  6486. * @returns {BufferAttributeNode}
  6487. */
  6488. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6489. /**
  6490. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6491. * Use this function if attribute data are updated per frame.
  6492. *
  6493. * @tsl
  6494. * @function
  6495. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6496. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6497. * @param {number} [stride=0] - The buffer stride.
  6498. * @param {number} [offset=0] - The buffer offset.
  6499. * @returns {BufferAttributeNode}
  6500. */
  6501. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6502. /**
  6503. * TSL function for creating a buffer attribute node but with enabled instancing
  6504. *
  6505. * @tsl
  6506. * @function
  6507. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6508. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6509. * @param {number} [stride=0] - The buffer stride.
  6510. * @param {number} [offset=0] - The buffer offset.
  6511. * @returns {BufferAttributeNode}
  6512. */
  6513. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6514. /**
  6515. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6516. *
  6517. * @tsl
  6518. * @function
  6519. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6520. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6521. * @param {number} [stride=0] - The buffer stride.
  6522. * @param {number} [offset=0] - The buffer offset.
  6523. * @returns {BufferAttributeNode}
  6524. */
  6525. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6526. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6527. /**
  6528. * TODO
  6529. *
  6530. * @augments Node
  6531. */
  6532. class ComputeNode extends Node {
  6533. static get type() {
  6534. return 'ComputeNode';
  6535. }
  6536. /**
  6537. * Constructs a new compute node.
  6538. *
  6539. * @param {Node} computeNode - TODO
  6540. * @param {Array<number>} workgroupSize - TODO.
  6541. */
  6542. constructor( computeNode, workgroupSize ) {
  6543. super( 'void' );
  6544. /**
  6545. * This flag can be used for type testing.
  6546. *
  6547. * @type {boolean}
  6548. * @readonly
  6549. * @default true
  6550. */
  6551. this.isComputeNode = true;
  6552. /**
  6553. * TODO
  6554. *
  6555. * @type {Node}
  6556. */
  6557. this.computeNode = computeNode;
  6558. /**
  6559. * TODO
  6560. *
  6561. * @type {Array<number>}
  6562. * @default [ 64 ]
  6563. */
  6564. this.workgroupSize = workgroupSize;
  6565. /**
  6566. * TODO
  6567. *
  6568. * @type {number}
  6569. */
  6570. this.count = null;
  6571. /**
  6572. * TODO
  6573. *
  6574. * @type {number}
  6575. */
  6576. this.version = 1;
  6577. /**
  6578. * The name or label of the uniform.
  6579. *
  6580. * @type {string}
  6581. * @default ''
  6582. */
  6583. this.name = '';
  6584. /**
  6585. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6586. * is executed once per object by default.
  6587. *
  6588. * @type {string}
  6589. * @default 'object'
  6590. */
  6591. this.updateBeforeType = NodeUpdateType.OBJECT;
  6592. /**
  6593. * TODO
  6594. *
  6595. * @type {?Function}
  6596. */
  6597. this.onInitFunction = null;
  6598. }
  6599. setCount( count ) {
  6600. this.count = count;
  6601. return this;
  6602. }
  6603. getCount() {
  6604. return this.count;
  6605. }
  6606. /**
  6607. * Executes the `dispose` event for this node.
  6608. */
  6609. dispose() {
  6610. this.dispatchEvent( { type: 'dispose' } );
  6611. }
  6612. /**
  6613. * Sets the {@link ComputeNode#name} property.
  6614. *
  6615. * @param {string} name - The name of the uniform.
  6616. * @return {ComputeNode} A reference to this node.
  6617. */
  6618. setName( name ) {
  6619. this.name = name;
  6620. return this;
  6621. }
  6622. /**
  6623. * Sets the {@link ComputeNode#name} property.
  6624. *
  6625. * @deprecated
  6626. * @param {string} name - The name of the uniform.
  6627. * @return {ComputeNode} A reference to this node.
  6628. */
  6629. label( name ) {
  6630. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6631. return this.setName( name );
  6632. }
  6633. /**
  6634. * TODO
  6635. *
  6636. * @param {Function} callback - TODO.
  6637. * @return {ComputeNode} A reference to this node.
  6638. */
  6639. onInit( callback ) {
  6640. this.onInitFunction = callback;
  6641. return this;
  6642. }
  6643. /**
  6644. * The method execute the compute for this node.
  6645. *
  6646. * @param {NodeFrame} frame - A reference to the current node frame.
  6647. */
  6648. updateBefore( { renderer } ) {
  6649. renderer.compute( this );
  6650. }
  6651. setup( builder ) {
  6652. const result = this.computeNode.build( builder );
  6653. if ( result ) {
  6654. const properties = builder.getNodeProperties( this );
  6655. properties.outputComputeNode = result.outputNode;
  6656. result.outputNode = null;
  6657. }
  6658. return result;
  6659. }
  6660. generate( builder, output ) {
  6661. const { shaderStage } = builder;
  6662. if ( shaderStage === 'compute' ) {
  6663. const snippet = this.computeNode.build( builder, 'void' );
  6664. if ( snippet !== '' ) {
  6665. builder.addLineFlowCode( snippet, this );
  6666. }
  6667. } else {
  6668. const properties = builder.getNodeProperties( this );
  6669. const outputComputeNode = properties.outputComputeNode;
  6670. if ( outputComputeNode ) {
  6671. return outputComputeNode.build( builder, output );
  6672. }
  6673. }
  6674. }
  6675. }
  6676. /**
  6677. * TSL function for creating a compute kernel node.
  6678. *
  6679. * @tsl
  6680. * @function
  6681. * @param {Node} node - TODO
  6682. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6683. * @returns {AtomicFunctionNode}
  6684. */
  6685. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  6686. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  6687. console.error( 'THREE.TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  6688. }
  6689. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  6690. const val = workgroupSize[ i ];
  6691. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  6692. console.error( `THREE.TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  6693. }
  6694. }
  6695. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  6696. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  6697. //
  6698. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  6699. };
  6700. /**
  6701. * TSL function for creating a compute node.
  6702. *
  6703. * @tsl
  6704. * @function
  6705. * @param {Node} node - TODO
  6706. * @param {number} count - TODO.
  6707. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6708. * @returns {AtomicFunctionNode}
  6709. */
  6710. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  6711. addMethodChaining( 'compute', compute );
  6712. addMethodChaining( 'computeKernel', computeKernel );
  6713. /**
  6714. * This node can be used as a cache management component for another node.
  6715. * Caching is in general used by default in {@link NodeBuilder} but this node
  6716. * allows the usage of a shared parent cache during the build process.
  6717. *
  6718. * @augments Node
  6719. */
  6720. class CacheNode extends Node {
  6721. static get type() {
  6722. return 'CacheNode';
  6723. }
  6724. /**
  6725. * Constructs a new cache node.
  6726. *
  6727. * @param {Node} node - The node that should be cached.
  6728. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6729. */
  6730. constructor( node, parent = true ) {
  6731. super();
  6732. /**
  6733. * The node that should be cached.
  6734. *
  6735. * @type {Node}
  6736. */
  6737. this.node = node;
  6738. /**
  6739. * Whether this node refers to a shared parent cache or not.
  6740. *
  6741. * @type {boolean}
  6742. * @default true
  6743. */
  6744. this.parent = parent;
  6745. /**
  6746. * This flag can be used for type testing.
  6747. *
  6748. * @type {boolean}
  6749. * @readonly
  6750. * @default true
  6751. */
  6752. this.isCacheNode = true;
  6753. }
  6754. getNodeType( builder ) {
  6755. const previousCache = builder.getCache();
  6756. const cache = builder.getCacheFromNode( this, this.parent );
  6757. builder.setCache( cache );
  6758. const nodeType = this.node.getNodeType( builder );
  6759. builder.setCache( previousCache );
  6760. return nodeType;
  6761. }
  6762. build( builder, ...params ) {
  6763. const previousCache = builder.getCache();
  6764. const cache = builder.getCacheFromNode( this, this.parent );
  6765. builder.setCache( cache );
  6766. const data = this.node.build( builder, ...params );
  6767. builder.setCache( previousCache );
  6768. return data;
  6769. }
  6770. }
  6771. /**
  6772. * TSL function for creating a cache node.
  6773. *
  6774. * @tsl
  6775. * @function
  6776. * @param {Node} node - The node that should be cached.
  6777. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6778. * @returns {CacheNode}
  6779. */
  6780. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6781. addMethodChaining( 'cache', cache );
  6782. /**
  6783. * The class generates the code of a given node but returns another node in the output.
  6784. * This can be used to call a method or node that does not return a value, i.e.
  6785. * type `void` on an input where returning a value is required. Example:
  6786. *
  6787. * ```js
  6788. * material.colorNode = myColor.bypass( runVoidFn() )
  6789. *```
  6790. *
  6791. * @augments Node
  6792. */
  6793. class BypassNode extends Node {
  6794. static get type() {
  6795. return 'BypassNode';
  6796. }
  6797. /**
  6798. * Constructs a new bypass node.
  6799. *
  6800. * @param {Node} outputNode - The output node.
  6801. * @param {Node} callNode - The call node.
  6802. */
  6803. constructor( outputNode, callNode ) {
  6804. super();
  6805. /**
  6806. * This flag can be used for type testing.
  6807. *
  6808. * @type {boolean}
  6809. * @readonly
  6810. * @default true
  6811. */
  6812. this.isBypassNode = true;
  6813. /**
  6814. * The output node.
  6815. *
  6816. * @type {Node}
  6817. */
  6818. this.outputNode = outputNode;
  6819. /**
  6820. * The call node.
  6821. *
  6822. * @type {Node}
  6823. */
  6824. this.callNode = callNode;
  6825. }
  6826. getNodeType( builder ) {
  6827. return this.outputNode.getNodeType( builder );
  6828. }
  6829. generate( builder ) {
  6830. const snippet = this.callNode.build( builder, 'void' );
  6831. if ( snippet !== '' ) {
  6832. builder.addLineFlowCode( snippet, this );
  6833. }
  6834. return this.outputNode.build( builder );
  6835. }
  6836. }
  6837. /**
  6838. * TSL function for creating a bypass node.
  6839. *
  6840. * @tsl
  6841. * @function
  6842. * @param {Node} outputNode - The output node.
  6843. * @param {Node} callNode - The call node.
  6844. * @returns {BypassNode}
  6845. */
  6846. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  6847. addMethodChaining( 'bypass', bypass );
  6848. /**
  6849. * This node allows to remap a node value from one range into another. E.g a value of
  6850. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6851. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6852. *
  6853. * @augments Node
  6854. */
  6855. class RemapNode extends Node {
  6856. static get type() {
  6857. return 'RemapNode';
  6858. }
  6859. /**
  6860. * Constructs a new remap node.
  6861. *
  6862. * @param {Node} node - The node that should be remapped.
  6863. * @param {Node} inLowNode - The source or current lower bound of the range.
  6864. * @param {Node} inHighNode - The source or current upper bound of the range.
  6865. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6866. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6867. */
  6868. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6869. super();
  6870. /**
  6871. * The node that should be remapped.
  6872. *
  6873. * @type {Node}
  6874. */
  6875. this.node = node;
  6876. /**
  6877. * The source or current lower bound of the range.
  6878. *
  6879. * @type {Node}
  6880. */
  6881. this.inLowNode = inLowNode;
  6882. /**
  6883. * The source or current upper bound of the range.
  6884. *
  6885. * @type {Node}
  6886. */
  6887. this.inHighNode = inHighNode;
  6888. /**
  6889. * The target lower bound of the range.
  6890. *
  6891. * @type {Node}
  6892. * @default float(0)
  6893. */
  6894. this.outLowNode = outLowNode;
  6895. /**
  6896. * The target upper bound of the range.
  6897. *
  6898. * @type {Node}
  6899. * @default float(1)
  6900. */
  6901. this.outHighNode = outHighNode;
  6902. /**
  6903. * Whether the node value should be clamped before
  6904. * remapping it to the target range.
  6905. *
  6906. * @type {boolean}
  6907. * @default true
  6908. */
  6909. this.doClamp = true;
  6910. }
  6911. setup() {
  6912. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6913. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6914. if ( doClamp === true ) t = t.clamp();
  6915. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6916. }
  6917. }
  6918. /**
  6919. * TSL function for creating a remap node.
  6920. *
  6921. * @tsl
  6922. * @function
  6923. * @param {Node} node - The node that should be remapped.
  6924. * @param {Node} inLowNode - The source or current lower bound of the range.
  6925. * @param {Node} inHighNode - The source or current upper bound of the range.
  6926. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6927. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6928. * @returns {RemapNode}
  6929. */
  6930. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  6931. /**
  6932. * TSL function for creating a remap node, but with enabled clamping.
  6933. *
  6934. * @tsl
  6935. * @function
  6936. * @param {Node} node - The node that should be remapped.
  6937. * @param {Node} inLowNode - The source or current lower bound of the range.
  6938. * @param {Node} inHighNode - The source or current upper bound of the range.
  6939. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6940. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6941. * @returns {RemapNode}
  6942. */
  6943. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  6944. addMethodChaining( 'remap', remap );
  6945. addMethodChaining( 'remapClamp', remapClamp );
  6946. /**
  6947. * This class can be used to implement basic expressions in shader code.
  6948. * Basic examples for that are `return`, `continue` or `discard` statements.
  6949. *
  6950. * @augments Node
  6951. */
  6952. class ExpressionNode extends Node {
  6953. static get type() {
  6954. return 'ExpressionNode';
  6955. }
  6956. /**
  6957. * Constructs a new expression node.
  6958. *
  6959. * @param {string} [snippet=''] - The native code snippet.
  6960. * @param {string} [nodeType='void'] - The node type.
  6961. */
  6962. constructor( snippet = '', nodeType = 'void' ) {
  6963. super( nodeType );
  6964. /**
  6965. * The native code snippet.
  6966. *
  6967. * @type {string}
  6968. * @default ''
  6969. */
  6970. this.snippet = snippet;
  6971. }
  6972. generate( builder, output ) {
  6973. const type = this.getNodeType( builder );
  6974. const snippet = this.snippet;
  6975. if ( type === 'void' ) {
  6976. builder.addLineFlowCode( snippet, this );
  6977. } else {
  6978. return builder.format( snippet, type, output );
  6979. }
  6980. }
  6981. }
  6982. /**
  6983. * TSL function for creating an expression node.
  6984. *
  6985. * @tsl
  6986. * @function
  6987. * @param {string} [snippet] - The native code snippet.
  6988. * @param {?string} [nodeType='void'] - The node type.
  6989. * @returns {ExpressionNode}
  6990. */
  6991. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  6992. /**
  6993. * Represents a `discard` shader operation in TSL.
  6994. *
  6995. * @tsl
  6996. * @function
  6997. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6998. * @return {Node} The `discard` expression.
  6999. */
  7000. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7001. /**
  7002. * Represents a `return` shader operation in TSL.
  7003. *
  7004. * @tsl
  7005. * @function
  7006. * @return {ExpressionNode} The `return` expression.
  7007. */
  7008. const Return = () => expression( 'return' ).toStack();
  7009. addMethodChaining( 'discard', Discard );
  7010. /**
  7011. * Normally, tone mapping and color conversion happens automatically
  7012. * before outputting pixel too the default (screen) framebuffer. In certain
  7013. * post processing setups this happens to late because certain effects
  7014. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7015. * to apply tone mapping and color space conversion at an arbitrary point
  7016. * in the effect chain.
  7017. *
  7018. * When applying tone mapping and color space conversion manually with this node,
  7019. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7020. *
  7021. * ```js
  7022. * const postProcessing = new PostProcessing( renderer );
  7023. * postProcessing.outputColorTransform = false;
  7024. *
  7025. * const scenePass = pass( scene, camera );
  7026. * const outputPass = renderOutput( scenePass );
  7027. *
  7028. * postProcessing.outputNode = outputPass;
  7029. * ```
  7030. *
  7031. * @augments TempNode
  7032. */
  7033. class RenderOutputNode extends TempNode {
  7034. static get type() {
  7035. return 'RenderOutputNode';
  7036. }
  7037. /**
  7038. * Constructs a new render output node.
  7039. *
  7040. * @param {Node} colorNode - The color node to process.
  7041. * @param {?number} toneMapping - The tone mapping type.
  7042. * @param {?string} outputColorSpace - The output color space.
  7043. */
  7044. constructor( colorNode, toneMapping, outputColorSpace ) {
  7045. super( 'vec4' );
  7046. /**
  7047. * The color node to process.
  7048. *
  7049. * @type {Node}
  7050. */
  7051. this.colorNode = colorNode;
  7052. /**
  7053. * The tone mapping type.
  7054. *
  7055. * @type {?number}
  7056. */
  7057. this.toneMapping = toneMapping;
  7058. /**
  7059. * The output color space.
  7060. *
  7061. * @type {?string}
  7062. */
  7063. this.outputColorSpace = outputColorSpace;
  7064. /**
  7065. * This flag can be used for type testing.
  7066. *
  7067. * @type {boolean}
  7068. * @readonly
  7069. * @default true
  7070. */
  7071. this.isRenderOutputNode = true;
  7072. }
  7073. setup( { context } ) {
  7074. let outputNode = this.colorNode || context.color;
  7075. // tone mapping
  7076. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  7077. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7078. if ( toneMapping !== NoToneMapping ) {
  7079. outputNode = outputNode.toneMapping( toneMapping );
  7080. }
  7081. // working to output color space
  7082. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7083. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7084. }
  7085. return outputNode;
  7086. }
  7087. }
  7088. /**
  7089. * TSL function for creating a posterize node.
  7090. *
  7091. * @tsl
  7092. * @function
  7093. * @param {Node} color - The color node to process.
  7094. * @param {?number} [toneMapping=null] - The tone mapping type.
  7095. * @param {?string} [outputColorSpace=null] - The output color space.
  7096. * @returns {RenderOutputNode}
  7097. */
  7098. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7099. addMethodChaining( 'renderOutput', renderOutput );
  7100. class DebugNode extends TempNode {
  7101. static get type() {
  7102. return 'DebugNode';
  7103. }
  7104. constructor( node, callback = null ) {
  7105. super();
  7106. this.node = node;
  7107. this.callback = callback;
  7108. }
  7109. getNodeType( builder ) {
  7110. return this.node.getNodeType( builder );
  7111. }
  7112. setup( builder ) {
  7113. return this.node.build( builder );
  7114. }
  7115. analyze( builder ) {
  7116. return this.node.build( builder );
  7117. }
  7118. generate( builder ) {
  7119. const callback = this.callback;
  7120. const snippet = this.node.build( builder );
  7121. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7122. const border = '-'.repeat( title.length );
  7123. let code = '';
  7124. code += '// #' + title + '#\n';
  7125. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7126. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7127. code += '// #' + border + '#\n';
  7128. if ( callback !== null ) {
  7129. callback( builder, code );
  7130. } else {
  7131. console.log( code );
  7132. }
  7133. return snippet;
  7134. }
  7135. }
  7136. /**
  7137. * TSL function for creating a debug node.
  7138. *
  7139. * @tsl
  7140. * @function
  7141. * @param {Node} node - The node to debug.
  7142. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7143. * @returns {DebugNode}
  7144. */
  7145. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7146. addMethodChaining( 'debug', debug );
  7147. // Non-PURE exports list, side-effects are required here.
  7148. // TSL Base Syntax
  7149. function addNodeElement( name/*, nodeElement*/ ) {
  7150. console.warn( 'THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7151. }
  7152. /**
  7153. * Base class for representing shader attributes as nodes.
  7154. *
  7155. * @augments Node
  7156. */
  7157. class AttributeNode extends Node {
  7158. static get type() {
  7159. return 'AttributeNode';
  7160. }
  7161. /**
  7162. * Constructs a new attribute node.
  7163. *
  7164. * @param {string} attributeName - The name of the attribute.
  7165. * @param {?string} nodeType - The node type.
  7166. */
  7167. constructor( attributeName, nodeType = null ) {
  7168. super( nodeType );
  7169. /**
  7170. * `AttributeNode` sets this property to `true` by default.
  7171. *
  7172. * @type {boolean}
  7173. * @default true
  7174. */
  7175. this.global = true;
  7176. this._attributeName = attributeName;
  7177. }
  7178. getHash( builder ) {
  7179. return this.getAttributeName( builder );
  7180. }
  7181. getNodeType( builder ) {
  7182. let nodeType = this.nodeType;
  7183. if ( nodeType === null ) {
  7184. const attributeName = this.getAttributeName( builder );
  7185. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7186. const attribute = builder.geometry.getAttribute( attributeName );
  7187. nodeType = builder.getTypeFromAttribute( attribute );
  7188. } else {
  7189. nodeType = 'float';
  7190. }
  7191. }
  7192. return nodeType;
  7193. }
  7194. /**
  7195. * Sets the attribute name to the given value. The method can be
  7196. * overwritten in derived classes if the final name must be computed
  7197. * analytically.
  7198. *
  7199. * @param {string} attributeName - The name of the attribute.
  7200. * @return {AttributeNode} A reference to this node.
  7201. */
  7202. setAttributeName( attributeName ) {
  7203. this._attributeName = attributeName;
  7204. return this;
  7205. }
  7206. /**
  7207. * Returns the attribute name of this node. The method can be
  7208. * overwritten in derived classes if the final name must be computed
  7209. * analytically.
  7210. *
  7211. * @param {NodeBuilder} builder - The current node builder.
  7212. * @return {string} The attribute name.
  7213. */
  7214. getAttributeName( /*builder*/ ) {
  7215. return this._attributeName;
  7216. }
  7217. generate( builder ) {
  7218. const attributeName = this.getAttributeName( builder );
  7219. const nodeType = this.getNodeType( builder );
  7220. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7221. if ( geometryAttribute === true ) {
  7222. const attribute = builder.geometry.getAttribute( attributeName );
  7223. const attributeType = builder.getTypeFromAttribute( attribute );
  7224. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7225. if ( builder.shaderStage === 'vertex' ) {
  7226. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7227. } else {
  7228. const nodeVarying = varying( this );
  7229. return nodeVarying.build( builder, nodeType );
  7230. }
  7231. } else {
  7232. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7233. return builder.generateConst( nodeType );
  7234. }
  7235. }
  7236. serialize( data ) {
  7237. super.serialize( data );
  7238. data.global = this.global;
  7239. data._attributeName = this._attributeName;
  7240. }
  7241. deserialize( data ) {
  7242. super.deserialize( data );
  7243. this.global = data.global;
  7244. this._attributeName = data._attributeName;
  7245. }
  7246. }
  7247. /**
  7248. * TSL function for creating an attribute node.
  7249. *
  7250. * @tsl
  7251. * @function
  7252. * @param {string} name - The name of the attribute.
  7253. * @param {?string} [nodeType=null] - The node type.
  7254. * @returns {AttributeNode}
  7255. */
  7256. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7257. /**
  7258. * TSL function for creating an uv attribute node with the given index.
  7259. *
  7260. * @tsl
  7261. * @function
  7262. * @param {number} [index=0] - The uv index.
  7263. * @return {AttributeNode<vec2>} The uv attribute node.
  7264. */
  7265. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7266. /**
  7267. * A node that represents the dimensions of a texture. The texture size is
  7268. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7269. * or `textureSize()`.
  7270. *
  7271. * @augments Node
  7272. */
  7273. class TextureSizeNode extends Node {
  7274. static get type() {
  7275. return 'TextureSizeNode';
  7276. }
  7277. /**
  7278. * Constructs a new texture size node.
  7279. *
  7280. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7281. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7282. */
  7283. constructor( textureNode, levelNode = null ) {
  7284. super( 'uvec2' );
  7285. /**
  7286. * This flag can be used for type testing.
  7287. *
  7288. * @type {boolean}
  7289. * @readonly
  7290. * @default true
  7291. */
  7292. this.isTextureSizeNode = true;
  7293. /**
  7294. * A texture node which size should be retrieved.
  7295. *
  7296. * @type {TextureNode}
  7297. */
  7298. this.textureNode = textureNode;
  7299. /**
  7300. * A level node which defines the requested mip.
  7301. *
  7302. * @type {Node<int>}
  7303. * @default null
  7304. */
  7305. this.levelNode = levelNode;
  7306. }
  7307. generate( builder, output ) {
  7308. const textureProperty = this.textureNode.build( builder, 'property' );
  7309. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7310. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7311. }
  7312. }
  7313. /**
  7314. * TSL function for creating a texture size node.
  7315. *
  7316. * @tsl
  7317. * @function
  7318. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7319. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7320. * @returns {TextureSizeNode}
  7321. */
  7322. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7323. /**
  7324. * A special type of uniform node that computes the
  7325. * maximum mipmap level for a given texture node.
  7326. *
  7327. * ```js
  7328. * const level = maxMipLevel( textureNode );
  7329. * ```
  7330. *
  7331. * @augments UniformNode
  7332. */
  7333. class MaxMipLevelNode extends UniformNode {
  7334. static get type() {
  7335. return 'MaxMipLevelNode';
  7336. }
  7337. /**
  7338. * Constructs a new max mip level node.
  7339. *
  7340. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7341. */
  7342. constructor( textureNode ) {
  7343. super( 0 );
  7344. /**
  7345. * The texture node to compute the max mip level for.
  7346. *
  7347. * @private
  7348. * @type {TextureNode}
  7349. */
  7350. this._textureNode = textureNode;
  7351. /**
  7352. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7353. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7354. *
  7355. * @type {string}
  7356. * @default 'frame'
  7357. */
  7358. this.updateType = NodeUpdateType.FRAME;
  7359. }
  7360. /**
  7361. * The texture node to compute the max mip level for.
  7362. *
  7363. * @readonly
  7364. * @type {TextureNode}
  7365. */
  7366. get textureNode() {
  7367. return this._textureNode;
  7368. }
  7369. /**
  7370. * The texture.
  7371. *
  7372. * @readonly
  7373. * @type {Texture}
  7374. */
  7375. get texture() {
  7376. return this._textureNode.value;
  7377. }
  7378. update() {
  7379. const texture = this.texture;
  7380. const images = texture.images;
  7381. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7382. if ( image && image.width !== undefined ) {
  7383. const { width, height } = image;
  7384. this.value = Math.log2( Math.max( width, height ) );
  7385. }
  7386. }
  7387. }
  7388. /**
  7389. * TSL function for creating a max mip level node.
  7390. *
  7391. * @tsl
  7392. * @function
  7393. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7394. * @returns {MaxMipLevelNode}
  7395. */
  7396. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7397. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7398. /**
  7399. * This type of uniform node represents a 2D texture.
  7400. *
  7401. * @augments UniformNode
  7402. */
  7403. class TextureNode extends UniformNode {
  7404. static get type() {
  7405. return 'TextureNode';
  7406. }
  7407. /**
  7408. * Constructs a new texture node.
  7409. *
  7410. * @param {Texture} [value=EmptyTexture] - The texture.
  7411. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7412. * @param {?Node<int>} [levelNode=null] - The level node.
  7413. * @param {?Node<float>} [biasNode=null] - The bias node.
  7414. */
  7415. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7416. super( value );
  7417. /**
  7418. * This flag can be used for type testing.
  7419. *
  7420. * @type {boolean}
  7421. * @readonly
  7422. * @default true
  7423. */
  7424. this.isTextureNode = true;
  7425. /**
  7426. * Represents the texture coordinates.
  7427. *
  7428. * @type {?Node<vec2|vec3>}
  7429. * @default null
  7430. */
  7431. this.uvNode = uvNode;
  7432. /**
  7433. * Represents the mip level that should be selected.
  7434. *
  7435. * @type {?Node<int>}
  7436. * @default null
  7437. */
  7438. this.levelNode = levelNode;
  7439. /**
  7440. * Represents the bias to be applied during level-of-detail computation.
  7441. *
  7442. * @type {?Node<float>}
  7443. * @default null
  7444. */
  7445. this.biasNode = biasNode;
  7446. /**
  7447. * Represents a reference value a texture sample is compared to.
  7448. *
  7449. * @type {?Node<float>}
  7450. * @default null
  7451. */
  7452. this.compareNode = null;
  7453. /**
  7454. * When using texture arrays, the depth node defines the layer to select.
  7455. *
  7456. * @type {?Node<int>}
  7457. * @default null
  7458. */
  7459. this.depthNode = null;
  7460. /**
  7461. * When defined, a texture is sampled using explicit gradients.
  7462. *
  7463. * @type {?Array<Node<vec2>>}
  7464. * @default null
  7465. */
  7466. this.gradNode = null;
  7467. /**
  7468. * Whether texture values should be sampled or fetched.
  7469. *
  7470. * @type {boolean}
  7471. * @default true
  7472. */
  7473. this.sampler = true;
  7474. /**
  7475. * Whether the uv transformation matrix should be
  7476. * automatically updated or not. Use `setUpdateMatrix()`
  7477. * if you want to change the value of the property.
  7478. *
  7479. * @type {boolean}
  7480. * @default false
  7481. */
  7482. this.updateMatrix = false;
  7483. /**
  7484. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7485. * sets the value to `frame` when the uv transformation matrix should
  7486. * automatically be updated.
  7487. *
  7488. * @type {string}
  7489. * @default 'none'
  7490. */
  7491. this.updateType = NodeUpdateType.NONE;
  7492. /**
  7493. * The reference node.
  7494. *
  7495. * @type {?Node}
  7496. * @default null
  7497. */
  7498. this.referenceNode = null;
  7499. /**
  7500. * The texture value is stored in a private property.
  7501. *
  7502. * @private
  7503. * @type {Texture}
  7504. */
  7505. this._value = value;
  7506. /**
  7507. * The uniform node that represents the uv transformation matrix.
  7508. *
  7509. * @private
  7510. * @type {?UniformNode<mat3>}
  7511. */
  7512. this._matrixUniform = null;
  7513. this.setUpdateMatrix( uvNode === null );
  7514. }
  7515. set value( value ) {
  7516. if ( this.referenceNode ) {
  7517. this.referenceNode.value = value;
  7518. } else {
  7519. this._value = value;
  7520. }
  7521. }
  7522. /**
  7523. * The texture value.
  7524. *
  7525. * @type {Texture}
  7526. */
  7527. get value() {
  7528. return this.referenceNode ? this.referenceNode.value : this._value;
  7529. }
  7530. /**
  7531. * Overwritten since the uniform hash is defined by the texture's UUID.
  7532. *
  7533. * @param {NodeBuilder} builder - The current node builder.
  7534. * @return {string} The uniform hash.
  7535. */
  7536. getUniformHash( /*builder*/ ) {
  7537. return this.value.uuid;
  7538. }
  7539. /**
  7540. * Overwritten since the node type is inferred from the texture type.
  7541. *
  7542. * @param {NodeBuilder} builder - The current node builder.
  7543. * @return {string} The node type.
  7544. */
  7545. getNodeType( /*builder*/ ) {
  7546. if ( this.value.isDepthTexture === true ) return 'float';
  7547. if ( this.value.type === UnsignedIntType ) {
  7548. return 'uvec4';
  7549. } else if ( this.value.type === IntType ) {
  7550. return 'ivec4';
  7551. }
  7552. return 'vec4';
  7553. }
  7554. /**
  7555. * Overwrites the default implementation to return a fixed value `'texture'`.
  7556. *
  7557. * @param {NodeBuilder} builder - The current node builder.
  7558. * @return {string} The input type.
  7559. */
  7560. getInputType( /*builder*/ ) {
  7561. return 'texture';
  7562. }
  7563. /**
  7564. * Returns a default uvs based on the current texture's channel.
  7565. *
  7566. * @return {AttributeNode<vec2>} The default uvs.
  7567. */
  7568. getDefaultUV() {
  7569. return uv$1( this.value.channel );
  7570. }
  7571. /**
  7572. * Overwritten to always return the texture reference of the node.
  7573. *
  7574. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7575. * @return {Texture} The texture reference.
  7576. */
  7577. updateReference( /*state*/ ) {
  7578. return this.value;
  7579. }
  7580. /**
  7581. * Transforms the given uv node with the texture transformation matrix.
  7582. *
  7583. * @param {Node} uvNode - The uv node to transform.
  7584. * @return {Node} The transformed uv node.
  7585. */
  7586. getTransformedUV( uvNode ) {
  7587. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7588. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7589. }
  7590. /**
  7591. * Defines whether the uv transformation matrix should automatically be updated or not.
  7592. *
  7593. * @param {boolean} value - The update toggle.
  7594. * @return {TextureNode} A reference to this node.
  7595. */
  7596. setUpdateMatrix( value ) {
  7597. this.updateMatrix = value;
  7598. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7599. return this;
  7600. }
  7601. /**
  7602. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7603. * to modify the uv node for correct sampling.
  7604. *
  7605. * @param {NodeBuilder} builder - The current node builder.
  7606. * @param {Node} uvNode - The uv node to setup.
  7607. * @return {Node} The updated uv node.
  7608. */
  7609. setupUV( builder, uvNode ) {
  7610. const texture = this.value;
  7611. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7612. if ( this.sampler ) {
  7613. uvNode = uvNode.flipY();
  7614. } else {
  7615. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7616. }
  7617. }
  7618. return uvNode;
  7619. }
  7620. /**
  7621. * Setups texture node by preparing the internal nodes for code generation.
  7622. *
  7623. * @param {NodeBuilder} builder - The current node builder.
  7624. */
  7625. setup( builder ) {
  7626. const properties = builder.getNodeProperties( this );
  7627. properties.referenceNode = this.referenceNode;
  7628. //
  7629. const texture = this.value;
  7630. if ( ! texture || texture.isTexture !== true ) {
  7631. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7632. }
  7633. //
  7634. let uvNode = this.uvNode;
  7635. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7636. uvNode = builder.context.getUV( this, builder );
  7637. }
  7638. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7639. if ( this.updateMatrix === true ) {
  7640. uvNode = this.getTransformedUV( uvNode );
  7641. }
  7642. uvNode = this.setupUV( builder, uvNode );
  7643. //
  7644. let levelNode = this.levelNode;
  7645. if ( levelNode === null && builder.context.getTextureLevel ) {
  7646. levelNode = builder.context.getTextureLevel( this );
  7647. }
  7648. //
  7649. properties.uvNode = uvNode;
  7650. properties.levelNode = levelNode;
  7651. properties.biasNode = this.biasNode;
  7652. properties.compareNode = this.compareNode;
  7653. properties.gradNode = this.gradNode;
  7654. properties.depthNode = this.depthNode;
  7655. }
  7656. /**
  7657. * Generates the uv code snippet.
  7658. *
  7659. * @param {NodeBuilder} builder - The current node builder.
  7660. * @param {Node} uvNode - The uv node to generate code for.
  7661. * @return {string} The generated code snippet.
  7662. */
  7663. generateUV( builder, uvNode ) {
  7664. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7665. }
  7666. /**
  7667. * Generates the snippet for the texture sampling.
  7668. *
  7669. * @param {NodeBuilder} builder - The current node builder.
  7670. * @param {string} textureProperty - The texture property.
  7671. * @param {string} uvSnippet - The uv snippet.
  7672. * @param {?string} levelSnippet - The level snippet.
  7673. * @param {?string} biasSnippet - The bias snippet.
  7674. * @param {?string} depthSnippet - The depth snippet.
  7675. * @param {?string} compareSnippet - The compare snippet.
  7676. * @param {?Array<string>} gradSnippet - The grad snippet.
  7677. * @return {string} The generated code snippet.
  7678. */
  7679. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  7680. const texture = this.value;
  7681. let snippet;
  7682. if ( levelSnippet ) {
  7683. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  7684. } else if ( biasSnippet ) {
  7685. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  7686. } else if ( gradSnippet ) {
  7687. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  7688. } else if ( compareSnippet ) {
  7689. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  7690. } else if ( this.sampler === false ) {
  7691. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  7692. } else {
  7693. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  7694. }
  7695. return snippet;
  7696. }
  7697. /**
  7698. * Generates the code snippet of the texture node.
  7699. *
  7700. * @param {NodeBuilder} builder - The current node builder.
  7701. * @param {string} output - The current output.
  7702. * @return {string} The generated code snippet.
  7703. */
  7704. generate( builder, output ) {
  7705. const texture = this.value;
  7706. const properties = builder.getNodeProperties( this );
  7707. const textureProperty = super.generate( builder, 'property' );
  7708. if ( /^sampler/.test( output ) ) {
  7709. return textureProperty + '_sampler';
  7710. } else if ( builder.isReference( output ) ) {
  7711. return textureProperty;
  7712. } else {
  7713. const nodeData = builder.getDataFromNode( this );
  7714. let propertyName = nodeData.propertyName;
  7715. if ( propertyName === undefined ) {
  7716. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  7717. const uvSnippet = this.generateUV( builder, uvNode );
  7718. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7719. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7720. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7721. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7722. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7723. const nodeVar = builder.getVarFromNode( this );
  7724. propertyName = builder.getPropertyName( nodeVar );
  7725. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7726. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7727. nodeData.snippet = snippet;
  7728. nodeData.propertyName = propertyName;
  7729. }
  7730. let snippet = propertyName;
  7731. const nodeType = this.getNodeType( builder );
  7732. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7733. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7734. }
  7735. return builder.format( snippet, nodeType, output );
  7736. }
  7737. }
  7738. /**
  7739. * Sets the sampler value.
  7740. *
  7741. * @param {boolean} value - The sampler value to set.
  7742. * @return {TextureNode} A reference to this texture node.
  7743. */
  7744. setSampler( value ) {
  7745. this.sampler = value;
  7746. return this;
  7747. }
  7748. /**
  7749. * Returns the sampler value.
  7750. *
  7751. * @return {boolean} The sampler value.
  7752. */
  7753. getSampler() {
  7754. return this.sampler;
  7755. }
  7756. // @TODO: Move to TSL
  7757. /**
  7758. * @function
  7759. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7760. *
  7761. * @param {Node} uvNode - The uv node.
  7762. * @return {TextureNode} A texture node representing the texture sample.
  7763. */
  7764. uv( uvNode ) { // @deprecated, r172
  7765. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7766. return this.sample( uvNode );
  7767. }
  7768. /**
  7769. * Samples the texture with the given uv node.
  7770. *
  7771. * @param {Node} uvNode - The uv node.
  7772. * @return {TextureNode} A texture node representing the texture sample.
  7773. */
  7774. sample( uvNode ) {
  7775. const textureNode = this.clone();
  7776. textureNode.uvNode = nodeObject( uvNode );
  7777. textureNode.referenceNode = this.getSelf();
  7778. return nodeObject( textureNode );
  7779. }
  7780. /**
  7781. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7782. *
  7783. * @param {Node<uvec2>} uvNode - The uv node.
  7784. * @returns {TextureNode} A texture node representing the texture load.
  7785. */
  7786. load( uvNode ) {
  7787. return this.sample( uvNode ).setSampler( false );
  7788. }
  7789. /**
  7790. * Samples a blurred version of the texture by defining an internal bias.
  7791. *
  7792. * @param {Node<float>} amountNode - How blurred the texture should be.
  7793. * @return {TextureNode} A texture node representing the texture sample.
  7794. */
  7795. blur( amountNode ) {
  7796. const textureNode = this.clone();
  7797. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7798. textureNode.referenceNode = this.getSelf();
  7799. const map = textureNode.value;
  7800. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  7801. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7802. textureNode.biasNode = null;
  7803. }
  7804. return nodeObject( textureNode );
  7805. }
  7806. /**
  7807. * Samples a specific mip of the texture.
  7808. *
  7809. * @param {Node<int>} levelNode - The mip level to sample.
  7810. * @return {TextureNode} A texture node representing the texture sample.
  7811. */
  7812. level( levelNode ) {
  7813. const textureNode = this.clone();
  7814. textureNode.levelNode = nodeObject( levelNode );
  7815. textureNode.referenceNode = this.getSelf();
  7816. return nodeObject( textureNode );
  7817. }
  7818. /**
  7819. * Returns the texture size of the requested level.
  7820. *
  7821. * @param {Node<int>} levelNode - The level to compute the size for.
  7822. * @return {TextureSizeNode} The texture size.
  7823. */
  7824. size( levelNode ) {
  7825. return textureSize( this, levelNode );
  7826. }
  7827. /**
  7828. * Samples the texture with the given bias.
  7829. *
  7830. * @param {Node<float>} biasNode - The bias node.
  7831. * @return {TextureNode} A texture node representing the texture sample.
  7832. */
  7833. bias( biasNode ) {
  7834. const textureNode = this.clone();
  7835. textureNode.biasNode = nodeObject( biasNode );
  7836. textureNode.referenceNode = this.getSelf();
  7837. return nodeObject( textureNode );
  7838. }
  7839. /**
  7840. * Samples the texture by executing a compare operation.
  7841. *
  7842. * @param {Node<float>} compareNode - The node that defines the compare value.
  7843. * @return {TextureNode} A texture node representing the texture sample.
  7844. */
  7845. compare( compareNode ) {
  7846. const textureNode = this.clone();
  7847. textureNode.compareNode = nodeObject( compareNode );
  7848. textureNode.referenceNode = this.getSelf();
  7849. return nodeObject( textureNode );
  7850. }
  7851. /**
  7852. * Samples the texture using an explicit gradient.
  7853. *
  7854. * @param {Node<vec2>} gradNodeX - The gradX node.
  7855. * @param {Node<vec2>} gradNodeY - The gradY node.
  7856. * @return {TextureNode} A texture node representing the texture sample.
  7857. */
  7858. grad( gradNodeX, gradNodeY ) {
  7859. const textureNode = this.clone();
  7860. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7861. textureNode.referenceNode = this.getSelf();
  7862. return nodeObject( textureNode );
  7863. }
  7864. /**
  7865. * Samples the texture by defining a depth node.
  7866. *
  7867. * @param {Node<int>} depthNode - The depth node.
  7868. * @return {TextureNode} A texture node representing the texture sample.
  7869. */
  7870. depth( depthNode ) {
  7871. const textureNode = this.clone();
  7872. textureNode.depthNode = nodeObject( depthNode );
  7873. textureNode.referenceNode = this.getSelf();
  7874. return nodeObject( textureNode );
  7875. }
  7876. // --
  7877. serialize( data ) {
  7878. super.serialize( data );
  7879. data.value = this.value.toJSON( data.meta ).uuid;
  7880. data.sampler = this.sampler;
  7881. data.updateMatrix = this.updateMatrix;
  7882. data.updateType = this.updateType;
  7883. }
  7884. deserialize( data ) {
  7885. super.deserialize( data );
  7886. this.value = data.meta.textures[ data.value ];
  7887. this.sampler = data.sampler;
  7888. this.updateMatrix = data.updateMatrix;
  7889. this.updateType = data.updateType;
  7890. }
  7891. /**
  7892. * The update is used to implement the update of the uv transformation matrix.
  7893. */
  7894. update() {
  7895. const texture = this.value;
  7896. const matrixUniform = this._matrixUniform;
  7897. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7898. if ( texture.matrixAutoUpdate === true ) {
  7899. texture.updateMatrix();
  7900. }
  7901. }
  7902. /**
  7903. * Clones the texture node.
  7904. *
  7905. * @return {TextureNode} The cloned texture node.
  7906. */
  7907. clone() {
  7908. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7909. newNode.sampler = this.sampler;
  7910. newNode.depthNode = this.depthNode;
  7911. newNode.compareNode = this.compareNode;
  7912. newNode.gradNode = this.gradNode;
  7913. return newNode;
  7914. }
  7915. }
  7916. /**
  7917. * TSL function for creating a texture node.
  7918. *
  7919. * @tsl
  7920. * @function
  7921. * @param {?Texture} value - The texture.
  7922. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7923. * @param {?Node<int>} [levelNode=null] - The level node.
  7924. * @param {?Node<float>} [biasNode=null] - The bias node.
  7925. * @returns {TextureNode}
  7926. */
  7927. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  7928. /**
  7929. * TSL function for creating a texture node or sample a texture node already existing.
  7930. *
  7931. * @tsl
  7932. * @function
  7933. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  7934. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7935. * @param {?Node<int>} [levelNode=null] - The level node.
  7936. * @param {?Node<float>} [biasNode=null] - The bias node.
  7937. * @returns {TextureNode}
  7938. */
  7939. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  7940. let textureNode;
  7941. if ( value && value.isTextureNode === true ) {
  7942. textureNode = nodeObject( value.clone() );
  7943. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  7944. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  7945. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  7946. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  7947. } else {
  7948. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  7949. }
  7950. return textureNode;
  7951. };
  7952. /**
  7953. * TSL function for creating a uniform texture node.
  7954. *
  7955. * @tsl
  7956. * @function
  7957. * @param {?Texture} value - The texture.
  7958. * @returns {TextureNode}
  7959. */
  7960. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  7961. /**
  7962. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7963. *
  7964. * @tsl
  7965. * @function
  7966. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  7967. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7968. * @param {?Node<int>} [levelNode=null] - The level node.
  7969. * @param {?Node<float>} [biasNode=null] - The bias node.
  7970. * @returns {TextureNode}
  7971. */
  7972. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7973. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7974. /**
  7975. * Converts a texture or texture node to a sampler.
  7976. *
  7977. * @tsl
  7978. * @function
  7979. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7980. * @returns {Node}
  7981. */
  7982. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  7983. /**
  7984. * Converts a texture or texture node to a sampler comparison.
  7985. *
  7986. * @tsl
  7987. * @function
  7988. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7989. * @returns {Node}
  7990. */
  7991. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  7992. /**
  7993. * A special type of uniform node which represents array-like data
  7994. * as uniform buffers. The access usually happens via `element()`
  7995. * which returns an instance of {@link ArrayElementNode}. For example:
  7996. *
  7997. * ```js
  7998. * const bufferNode = buffer( array, 'mat4', count );
  7999. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8000. * ```
  8001. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8002. * since it handles more input types and automatically cares about buffer paddings.
  8003. *
  8004. * @augments UniformNode
  8005. */
  8006. class BufferNode extends UniformNode {
  8007. static get type() {
  8008. return 'BufferNode';
  8009. }
  8010. /**
  8011. * Constructs a new buffer node.
  8012. *
  8013. * @param {Array<number>} value - Array-like buffer data.
  8014. * @param {string} bufferType - The data type of the buffer.
  8015. * @param {number} [bufferCount=0] - The count of buffer elements.
  8016. */
  8017. constructor( value, bufferType, bufferCount = 0 ) {
  8018. super( value, bufferType );
  8019. /**
  8020. * This flag can be used for type testing.
  8021. *
  8022. * @type {boolean}
  8023. * @readonly
  8024. * @default true
  8025. */
  8026. this.isBufferNode = true;
  8027. /**
  8028. * The data type of the buffer.
  8029. *
  8030. * @type {string}
  8031. */
  8032. this.bufferType = bufferType;
  8033. /**
  8034. * The uniform node that holds the value of the reference node.
  8035. *
  8036. * @type {number}
  8037. * @default 0
  8038. */
  8039. this.bufferCount = bufferCount;
  8040. }
  8041. /**
  8042. * The data type of the buffer elements.
  8043. *
  8044. * @param {NodeBuilder} builder - The current node builder.
  8045. * @return {string} The element type.
  8046. */
  8047. getElementType( builder ) {
  8048. return this.getNodeType( builder );
  8049. }
  8050. /**
  8051. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8052. *
  8053. * @param {NodeBuilder} builder - The current node builder.
  8054. * @return {string} The input type.
  8055. */
  8056. getInputType( /*builder*/ ) {
  8057. return 'buffer';
  8058. }
  8059. }
  8060. /**
  8061. * TSL function for creating a buffer node.
  8062. *
  8063. * @tsl
  8064. * @function
  8065. * @param {Array} value - Array-like buffer data.
  8066. * @param {string} type - The data type of a buffer element.
  8067. * @param {number} count - The count of buffer elements.
  8068. * @returns {BufferNode}
  8069. */
  8070. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8071. /**
  8072. * Represents the element access on uniform array nodes.
  8073. *
  8074. * @augments ArrayElementNode
  8075. */
  8076. class UniformArrayElementNode extends ArrayElementNode {
  8077. static get type() {
  8078. return 'UniformArrayElementNode';
  8079. }
  8080. /**
  8081. * Constructs a new buffer node.
  8082. *
  8083. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8084. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8085. */
  8086. constructor( uniformArrayNode, indexNode ) {
  8087. super( uniformArrayNode, indexNode );
  8088. /**
  8089. * This flag can be used for type testing.
  8090. *
  8091. * @type {boolean}
  8092. * @readonly
  8093. * @default true
  8094. */
  8095. this.isArrayBufferElementNode = true;
  8096. }
  8097. generate( builder ) {
  8098. const snippet = super.generate( builder );
  8099. const type = this.getNodeType();
  8100. const paddedType = this.node.getPaddedType();
  8101. return builder.format( snippet, paddedType, type );
  8102. }
  8103. }
  8104. /**
  8105. * Similar to {@link BufferNode} this module represents array-like data as
  8106. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8107. * data types in the array (e.g `three.js` primitives) and automatically
  8108. * manage buffer padding. It should be the first choice when working with
  8109. * uniforms buffers.
  8110. * ```js
  8111. * const tintColors = uniformArray( [
  8112. * new Color( 1, 0, 0 ),
  8113. * new Color( 0, 1, 0 ),
  8114. * new Color( 0, 0, 1 )
  8115. * ], 'color' );
  8116. *
  8117. * const redColor = tintColors.element( 0 );
  8118. *
  8119. * @augments BufferNode
  8120. */
  8121. class UniformArrayNode extends BufferNode {
  8122. static get type() {
  8123. return 'UniformArrayNode';
  8124. }
  8125. /**
  8126. * Constructs a new uniform array node.
  8127. *
  8128. * @param {Array<any>} value - Array holding the buffer data.
  8129. * @param {?string} [elementType=null] - The data type of a buffer element.
  8130. */
  8131. constructor( value, elementType = null ) {
  8132. super( null );
  8133. /**
  8134. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8135. * hold number primitives as well as three.js objects like vectors, matrices
  8136. * or colors.
  8137. *
  8138. * @type {Array<any>}
  8139. */
  8140. this.array = value;
  8141. /**
  8142. * The data type of an array element.
  8143. *
  8144. * @type {string}
  8145. */
  8146. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8147. /**
  8148. * The padded type. Uniform buffers must conform to a certain buffer layout
  8149. * so a separate type is computed to ensure correct buffer size.
  8150. *
  8151. * @type {string}
  8152. */
  8153. this.paddedType = this.getPaddedType();
  8154. /**
  8155. * Overwritten since uniform array nodes are updated per render.
  8156. *
  8157. * @type {string}
  8158. * @default 'render'
  8159. */
  8160. this.updateType = NodeUpdateType.RENDER;
  8161. /**
  8162. * This flag can be used for type testing.
  8163. *
  8164. * @type {boolean}
  8165. * @readonly
  8166. * @default true
  8167. */
  8168. this.isArrayBufferNode = true;
  8169. }
  8170. /**
  8171. * This method is overwritten since the node type is inferred from the
  8172. * {@link UniformArrayNode#paddedType}.
  8173. *
  8174. * @param {NodeBuilder} builder - The current node builder.
  8175. * @return {string} The node type.
  8176. */
  8177. getNodeType( /*builder*/ ) {
  8178. return this.paddedType;
  8179. }
  8180. /**
  8181. * The data type of the array elements.
  8182. *
  8183. * @param {NodeBuilder} builder - The current node builder.
  8184. * @return {string} The element type.
  8185. */
  8186. getElementType() {
  8187. return this.elementType;
  8188. }
  8189. /**
  8190. * Returns the padded type based on the element type.
  8191. *
  8192. * @return {string} The padded type.
  8193. */
  8194. getPaddedType() {
  8195. const elementType = this.elementType;
  8196. let paddedType = 'vec4';
  8197. if ( elementType === 'mat2' ) {
  8198. paddedType = 'mat2';
  8199. } else if ( /mat/.test( elementType ) === true ) {
  8200. paddedType = 'mat4';
  8201. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8202. paddedType = 'ivec4';
  8203. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8204. paddedType = 'uvec4';
  8205. }
  8206. return paddedType;
  8207. }
  8208. /**
  8209. * The update makes sure to correctly transfer the data from the (complex) objects
  8210. * in the array to the internal, correctly padded value buffer.
  8211. *
  8212. * @param {NodeFrame} frame - A reference to the current node frame.
  8213. */
  8214. update( /*frame*/ ) {
  8215. const { array, value } = this;
  8216. const elementType = this.elementType;
  8217. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8218. for ( let i = 0; i < array.length; i ++ ) {
  8219. const index = i * 4;
  8220. value[ index ] = array[ i ];
  8221. }
  8222. } else if ( elementType === 'color' ) {
  8223. for ( let i = 0; i < array.length; i ++ ) {
  8224. const index = i * 4;
  8225. const vector = array[ i ];
  8226. value[ index ] = vector.r;
  8227. value[ index + 1 ] = vector.g;
  8228. value[ index + 2 ] = vector.b || 0;
  8229. //value[ index + 3 ] = vector.a || 0;
  8230. }
  8231. } else if ( elementType === 'mat2' ) {
  8232. for ( let i = 0; i < array.length; i ++ ) {
  8233. const index = i * 4;
  8234. const matrix = array[ i ];
  8235. value[ index ] = matrix.elements[ 0 ];
  8236. value[ index + 1 ] = matrix.elements[ 1 ];
  8237. value[ index + 2 ] = matrix.elements[ 2 ];
  8238. value[ index + 3 ] = matrix.elements[ 3 ];
  8239. }
  8240. } else if ( elementType === 'mat3' ) {
  8241. for ( let i = 0; i < array.length; i ++ ) {
  8242. const index = i * 16;
  8243. const matrix = array[ i ];
  8244. value[ index ] = matrix.elements[ 0 ];
  8245. value[ index + 1 ] = matrix.elements[ 1 ];
  8246. value[ index + 2 ] = matrix.elements[ 2 ];
  8247. value[ index + 4 ] = matrix.elements[ 3 ];
  8248. value[ index + 5 ] = matrix.elements[ 4 ];
  8249. value[ index + 6 ] = matrix.elements[ 5 ];
  8250. value[ index + 8 ] = matrix.elements[ 6 ];
  8251. value[ index + 9 ] = matrix.elements[ 7 ];
  8252. value[ index + 10 ] = matrix.elements[ 8 ];
  8253. value[ index + 15 ] = 1;
  8254. }
  8255. } else if ( elementType === 'mat4' ) {
  8256. for ( let i = 0; i < array.length; i ++ ) {
  8257. const index = i * 16;
  8258. const matrix = array[ i ];
  8259. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8260. value[ index + i ] = matrix.elements[ i ];
  8261. }
  8262. }
  8263. } else {
  8264. for ( let i = 0; i < array.length; i ++ ) {
  8265. const index = i * 4;
  8266. const vector = array[ i ];
  8267. value[ index ] = vector.x;
  8268. value[ index + 1 ] = vector.y;
  8269. value[ index + 2 ] = vector.z || 0;
  8270. value[ index + 3 ] = vector.w || 0;
  8271. }
  8272. }
  8273. }
  8274. /**
  8275. * Implement the value buffer creation based on the array data.
  8276. *
  8277. * @param {NodeBuilder} builder - A reference to the current node builder.
  8278. * @return {null}
  8279. */
  8280. setup( builder ) {
  8281. const length = this.array.length;
  8282. const elementType = this.elementType;
  8283. let arrayType = Float32Array;
  8284. const paddedType = this.paddedType;
  8285. const paddedElementLength = builder.getTypeLength( paddedType );
  8286. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8287. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8288. this.value = new arrayType( length * paddedElementLength );
  8289. this.bufferCount = length;
  8290. this.bufferType = paddedType;
  8291. return super.setup( builder );
  8292. }
  8293. /**
  8294. * Overwrites the default `element()` method to provide element access
  8295. * based on {@link UniformArrayNode}.
  8296. *
  8297. * @param {IndexNode} indexNode - The index node.
  8298. * @return {UniformArrayElementNode}
  8299. */
  8300. element( indexNode ) {
  8301. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8302. }
  8303. }
  8304. /**
  8305. * TSL function for creating an uniform array node.
  8306. *
  8307. * @tsl
  8308. * @function
  8309. * @param {Array<any>} values - Array-like data.
  8310. * @param {?string} [nodeType] - The data type of the array elements.
  8311. * @returns {UniformArrayNode}
  8312. */
  8313. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8314. /**
  8315. * The node allows to set values for built-in shader variables. That is
  8316. * required for features like hardware-accelerated vertex clipping.
  8317. *
  8318. * @augments Node
  8319. */
  8320. class BuiltinNode extends Node {
  8321. /**
  8322. * Constructs a new builtin node.
  8323. *
  8324. * @param {string} name - The name of the built-in shader variable.
  8325. */
  8326. constructor( name ) {
  8327. super( 'float' );
  8328. /**
  8329. * The name of the built-in shader variable.
  8330. *
  8331. * @type {string}
  8332. */
  8333. this.name = name;
  8334. /**
  8335. * This flag can be used for type testing.
  8336. *
  8337. * @type {boolean}
  8338. * @readonly
  8339. * @default true
  8340. */
  8341. this.isBuiltinNode = true;
  8342. }
  8343. /**
  8344. * Generates the code snippet of the builtin node.
  8345. *
  8346. * @param {NodeBuilder} builder - The current node builder.
  8347. * @return {string} The generated code snippet.
  8348. */
  8349. generate( /* builder */ ) {
  8350. return this.name;
  8351. }
  8352. }
  8353. /**
  8354. * TSL function for creating a builtin node.
  8355. *
  8356. * @tsl
  8357. * @function
  8358. * @param {string} name - The name of the built-in shader variable.
  8359. * @returns {BuiltinNode}
  8360. */
  8361. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8362. /**
  8363. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  8364. *
  8365. * @tsl
  8366. * @type {UniformNode<uint>}
  8367. */
  8368. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  8369. /**
  8370. * TSL object that represents the `near` value of the camera used for the current render.
  8371. *
  8372. * @tsl
  8373. * @type {UniformNode<float>}
  8374. */
  8375. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  8376. /**
  8377. * TSL object that represents the `far` value of the camera used for the current render.
  8378. *
  8379. * @tsl
  8380. * @type {UniformNode<float>}
  8381. */
  8382. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  8383. /**
  8384. * TSL object that represents the projection matrix of the camera used for the current render.
  8385. *
  8386. * @tsl
  8387. * @type {UniformNode<mat4>}
  8388. */
  8389. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8390. let cameraProjectionMatrix;
  8391. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8392. const matrices = [];
  8393. for ( const subCamera of camera.cameras ) {
  8394. matrices.push( subCamera.projectionMatrix );
  8395. }
  8396. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  8397. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrix' );
  8398. } else {
  8399. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  8400. }
  8401. return cameraProjectionMatrix;
  8402. } ).once() )();
  8403. /**
  8404. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8405. *
  8406. * @tsl
  8407. * @type {UniformNode<mat4>}
  8408. */
  8409. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8410. let cameraProjectionMatrixInverse;
  8411. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8412. const matrices = [];
  8413. for ( const subCamera of camera.cameras ) {
  8414. matrices.push( subCamera.projectionMatrixInverse );
  8415. }
  8416. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  8417. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrixInverse' );
  8418. } else {
  8419. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8420. }
  8421. return cameraProjectionMatrixInverse;
  8422. } ).once() )();
  8423. /**
  8424. * TSL object that represents the view matrix of the camera used for the current render.
  8425. *
  8426. * @tsl
  8427. * @type {UniformNode<mat4>}
  8428. */
  8429. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8430. let cameraViewMatrix;
  8431. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8432. const matrices = [];
  8433. for ( const subCamera of camera.cameras ) {
  8434. matrices.push( subCamera.matrixWorldInverse );
  8435. }
  8436. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  8437. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraViewMatrix' );
  8438. } else {
  8439. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8440. }
  8441. return cameraViewMatrix;
  8442. } ).once() )();
  8443. /**
  8444. * TSL object that represents the world matrix of the camera used for the current render.
  8445. *
  8446. * @tsl
  8447. * @type {UniformNode<mat4>}
  8448. */
  8449. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8450. /**
  8451. * TSL object that represents the normal matrix of the camera used for the current render.
  8452. *
  8453. * @tsl
  8454. * @type {UniformNode<mat3>}
  8455. */
  8456. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8457. /**
  8458. * TSL object that represents the position in world space of the camera used for the current render.
  8459. *
  8460. * @tsl
  8461. * @type {UniformNode<vec3>}
  8462. */
  8463. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8464. const _sphere = /*@__PURE__*/ new Sphere();
  8465. /**
  8466. * This node can be used to access transformation related metrics of 3D objects.
  8467. * Depending on the selected scope, a different metric is represented as a uniform
  8468. * in the shader. The following scopes are supported:
  8469. *
  8470. * - `POSITION`: The object's position in world space.
  8471. * - `VIEW_POSITION`: The object's position in view/camera space.
  8472. * - `DIRECTION`: The object's direction in world space.
  8473. * - `SCALE`: The object's scale in world space.
  8474. * - `WORLD_MATRIX`: The object's matrix in world space.
  8475. *
  8476. * @augments Node
  8477. */
  8478. class Object3DNode extends Node {
  8479. static get type() {
  8480. return 'Object3DNode';
  8481. }
  8482. /**
  8483. * Constructs a new object 3D node.
  8484. *
  8485. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8486. * @param {?Object3D} [object3d=null] - The 3D object.
  8487. */
  8488. constructor( scope, object3d = null ) {
  8489. super();
  8490. /**
  8491. * The node reports a different type of transformation depending on the scope.
  8492. *
  8493. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  8494. */
  8495. this.scope = scope;
  8496. /**
  8497. * The 3D object.
  8498. *
  8499. * @type {?Object3D}
  8500. * @default null
  8501. */
  8502. this.object3d = object3d;
  8503. /**
  8504. * Overwritten since this type of node is updated per object.
  8505. *
  8506. * @type {string}
  8507. * @default 'object'
  8508. */
  8509. this.updateType = NodeUpdateType.OBJECT;
  8510. /**
  8511. * Holds the value of the node as a uniform.
  8512. *
  8513. * @type {UniformNode}
  8514. */
  8515. this.uniformNode = new UniformNode( null );
  8516. }
  8517. /**
  8518. * Overwritten since the node type is inferred from the scope.
  8519. *
  8520. * @return {string} The node type.
  8521. */
  8522. getNodeType() {
  8523. const scope = this.scope;
  8524. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8525. return 'mat4';
  8526. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8527. return 'vec3';
  8528. } else if ( scope === Object3DNode.RADIUS ) {
  8529. return 'float';
  8530. }
  8531. }
  8532. /**
  8533. * Updates the uniform value depending on the scope.
  8534. *
  8535. * @param {NodeFrame} frame - The current node frame.
  8536. */
  8537. update( frame ) {
  8538. const object = this.object3d;
  8539. const uniformNode = this.uniformNode;
  8540. const scope = this.scope;
  8541. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8542. uniformNode.value = object.matrixWorld;
  8543. } else if ( scope === Object3DNode.POSITION ) {
  8544. uniformNode.value = uniformNode.value || new Vector3();
  8545. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8546. } else if ( scope === Object3DNode.SCALE ) {
  8547. uniformNode.value = uniformNode.value || new Vector3();
  8548. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  8549. } else if ( scope === Object3DNode.DIRECTION ) {
  8550. uniformNode.value = uniformNode.value || new Vector3();
  8551. object.getWorldDirection( uniformNode.value );
  8552. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  8553. const camera = frame.camera;
  8554. uniformNode.value = uniformNode.value || new Vector3();
  8555. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8556. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  8557. } else if ( scope === Object3DNode.RADIUS ) {
  8558. const geometry = frame.object.geometry;
  8559. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8560. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8561. uniformNode.value = _sphere.radius;
  8562. }
  8563. }
  8564. /**
  8565. * Generates the code snippet of the uniform node. The node type of the uniform
  8566. * node also depends on the selected scope.
  8567. *
  8568. * @param {NodeBuilder} builder - The current node builder.
  8569. * @return {string} The generated code snippet.
  8570. */
  8571. generate( builder ) {
  8572. const scope = this.scope;
  8573. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8574. this.uniformNode.nodeType = 'mat4';
  8575. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8576. this.uniformNode.nodeType = 'vec3';
  8577. } else if ( scope === Object3DNode.RADIUS ) {
  8578. this.uniformNode.nodeType = 'float';
  8579. }
  8580. return this.uniformNode.build( builder );
  8581. }
  8582. serialize( data ) {
  8583. super.serialize( data );
  8584. data.scope = this.scope;
  8585. }
  8586. deserialize( data ) {
  8587. super.deserialize( data );
  8588. this.scope = data.scope;
  8589. }
  8590. }
  8591. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  8592. Object3DNode.POSITION = 'position';
  8593. Object3DNode.SCALE = 'scale';
  8594. Object3DNode.VIEW_POSITION = 'viewPosition';
  8595. Object3DNode.DIRECTION = 'direction';
  8596. Object3DNode.RADIUS = 'radius';
  8597. /**
  8598. * TSL function for creating an object 3D node that represents the object's direction in world space.
  8599. *
  8600. * @tsl
  8601. * @function
  8602. * @param {?Object3D} [object3d] - The 3D object.
  8603. * @returns {Object3DNode<vec3>}
  8604. */
  8605. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  8606. /**
  8607. * TSL function for creating an object 3D node that represents the object's world matrix.
  8608. *
  8609. * @tsl
  8610. * @function
  8611. * @param {?Object3D} [object3d] - The 3D object.
  8612. * @returns {Object3DNode<mat4>}
  8613. */
  8614. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  8615. /**
  8616. * TSL function for creating an object 3D node that represents the object's position in world space.
  8617. *
  8618. * @tsl
  8619. * @function
  8620. * @param {?Object3D} [object3d] - The 3D object.
  8621. * @returns {Object3DNode<vec3>}
  8622. */
  8623. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  8624. /**
  8625. * TSL function for creating an object 3D node that represents the object's scale in world space.
  8626. *
  8627. * @tsl
  8628. * @function
  8629. * @param {?Object3D} [object3d] - The 3D object.
  8630. * @returns {Object3DNode<vec3>}
  8631. */
  8632. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  8633. /**
  8634. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  8635. *
  8636. * @tsl
  8637. * @function
  8638. * @param {?Object3D} [object3d] - The 3D object.
  8639. * @returns {Object3DNode<vec3>}
  8640. */
  8641. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  8642. /**
  8643. * TSL function for creating an object 3D node that represents the object's radius.
  8644. *
  8645. * @tsl
  8646. * @function
  8647. * @param {?Object3D} [object3d] - The 3D object.
  8648. * @returns {Object3DNode<float>}
  8649. */
  8650. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  8651. /**
  8652. * This type of node is a specialized version of `Object3DNode`
  8653. * with larger set of model related metrics. Unlike `Object3DNode`,
  8654. * `ModelNode` extracts the reference to the 3D object from the
  8655. * current node frame state.
  8656. *
  8657. * @augments Object3DNode
  8658. */
  8659. class ModelNode extends Object3DNode {
  8660. static get type() {
  8661. return 'ModelNode';
  8662. }
  8663. /**
  8664. * Constructs a new object model node.
  8665. *
  8666. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8667. */
  8668. constructor( scope ) {
  8669. super( scope );
  8670. }
  8671. /**
  8672. * Extracts the model reference from the frame state and then
  8673. * updates the uniform value depending on the scope.
  8674. *
  8675. * @param {NodeFrame} frame - The current node frame.
  8676. */
  8677. update( frame ) {
  8678. this.object3d = frame.object;
  8679. super.update( frame );
  8680. }
  8681. }
  8682. /**
  8683. * TSL object that represents the object's direction in world space.
  8684. *
  8685. * @tsl
  8686. * @type {ModelNode<vec3>}
  8687. */
  8688. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  8689. /**
  8690. * TSL object that represents the object's world matrix.
  8691. *
  8692. * @tsl
  8693. * @type {ModelNode<mat4>}
  8694. */
  8695. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  8696. /**
  8697. * TSL object that represents the object's position in world space.
  8698. *
  8699. * @tsl
  8700. * @type {ModelNode<vec3>}
  8701. */
  8702. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  8703. /**
  8704. * TSL object that represents the object's scale in world space.
  8705. *
  8706. * @tsl
  8707. * @type {ModelNode<vec3>}
  8708. */
  8709. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  8710. /**
  8711. * TSL object that represents the object's position in view/camera space.
  8712. *
  8713. * @tsl
  8714. * @type {ModelNode<vec3>}
  8715. */
  8716. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  8717. /**
  8718. * TSL object that represents the object's radius.
  8719. *
  8720. * @tsl
  8721. * @type {ModelNode<float>}
  8722. */
  8723. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  8724. /**
  8725. * TSL object that represents the object's normal matrix.
  8726. *
  8727. * @tsl
  8728. * @type {UniformNode<mat3>}
  8729. */
  8730. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  8731. /**
  8732. * TSL object that represents the object's inverse world matrix.
  8733. *
  8734. * @tsl
  8735. * @type {UniformNode<mat4>}
  8736. */
  8737. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  8738. /**
  8739. * TSL object that represents the object's model view matrix.
  8740. *
  8741. * @tsl
  8742. * @type {Node<mat4>}
  8743. */
  8744. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8745. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  8746. } ).once() )().toVar( 'modelViewMatrix' );
  8747. // GPU Precision
  8748. /**
  8749. * TSL object that represents the object's model view in `mediump` precision.
  8750. *
  8751. * @tsl
  8752. * @type {Node<mat4>}
  8753. */
  8754. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  8755. // CPU Precision
  8756. /**
  8757. * TSL object that represents the object's model view in `highp` precision
  8758. * which is achieved by computing the matrix in JS and not in the shader.
  8759. *
  8760. * @tsl
  8761. * @type {Node<mat4>}
  8762. */
  8763. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8764. builder.context.isHighPrecisionModelViewMatrix = true;
  8765. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  8766. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8767. } );
  8768. } ).once() )().toVar( 'highpModelViewMatrix' );
  8769. /**
  8770. * TSL object that represents the object's model normal view in `highp` precision
  8771. * which is achieved by computing the matrix in JS and not in the shader.
  8772. *
  8773. * @tsl
  8774. * @type {Node<mat3>}
  8775. */
  8776. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8777. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  8778. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  8779. if ( isHighPrecisionModelViewMatrix !== true ) {
  8780. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8781. }
  8782. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  8783. } );
  8784. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  8785. /**
  8786. * TSL object that represents the position attribute of the current rendered object.
  8787. *
  8788. * @tsl
  8789. * @type {AttributeNode<vec3>}
  8790. */
  8791. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  8792. /**
  8793. * TSL object that represents the vertex position in local space of the current rendered object.
  8794. *
  8795. * @tsl
  8796. * @type {AttributeNode<vec3>}
  8797. */
  8798. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  8799. /**
  8800. * TSL object that represents the previous vertex position in local space of the current rendered object.
  8801. * Used in context of {@link VelocityNode} for rendering motion vectors.
  8802. *
  8803. * @tsl
  8804. * @type {AttributeNode<vec3>}
  8805. */
  8806. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  8807. /**
  8808. * TSL object that represents the vertex position in world space of the current rendered object.
  8809. *
  8810. * @tsl
  8811. * @type {VaryingNode<vec3>}
  8812. */
  8813. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  8814. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  8815. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  8816. /**
  8817. * TSL object that represents the position world direction of the current rendered object.
  8818. *
  8819. * @tsl
  8820. * @type {Node<vec3>}
  8821. */
  8822. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  8823. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  8824. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  8825. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  8826. /**
  8827. * TSL object that represents the vertex position in view space of the current rendered object.
  8828. *
  8829. * @tsl
  8830. * @type {VaryingNode<vec3>}
  8831. */
  8832. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8833. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  8834. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  8835. /**
  8836. * TSL object that represents the position view direction of the current rendered object.
  8837. *
  8838. * @tsl
  8839. * @type {VaryingNode<vec3>}
  8840. */
  8841. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  8842. /**
  8843. * This node can be used to evaluate whether a primitive is front or back facing.
  8844. *
  8845. * @augments Node
  8846. */
  8847. class FrontFacingNode extends Node {
  8848. static get type() {
  8849. return 'FrontFacingNode';
  8850. }
  8851. /**
  8852. * Constructs a new front facing node.
  8853. */
  8854. constructor() {
  8855. super( 'bool' );
  8856. /**
  8857. * This flag can be used for type testing.
  8858. *
  8859. * @type {boolean}
  8860. * @readonly
  8861. * @default true
  8862. */
  8863. this.isFrontFacingNode = true;
  8864. }
  8865. generate( builder ) {
  8866. if ( builder.shaderStage !== 'fragment' ) return 'true';
  8867. //
  8868. const { renderer, material } = builder;
  8869. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  8870. if ( material.side === BackSide ) {
  8871. return 'false';
  8872. }
  8873. }
  8874. return builder.getFrontFacing();
  8875. }
  8876. }
  8877. /**
  8878. * TSL object that represents whether a primitive is front or back facing
  8879. *
  8880. * @tsl
  8881. * @type {FrontFacingNode<bool>}
  8882. */
  8883. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  8884. /**
  8885. * TSL object that represents the front facing status as a number instead of a bool.
  8886. * `1` means front facing, `-1` means back facing.
  8887. *
  8888. * @tsl
  8889. * @type {Node<float>}
  8890. */
  8891. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8892. /**
  8893. * Converts a direction vector to a face direction vector based on the material's side.
  8894. *
  8895. * If the material is set to `BackSide`, the direction is inverted.
  8896. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  8897. *
  8898. * @tsl
  8899. * @param {Node<vec3>} direction - The direction vector to convert.
  8900. * @returns {Node<vec3>} The converted direction vector.
  8901. */
  8902. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  8903. const side = material.side;
  8904. if ( side === BackSide ) {
  8905. direction = direction.mul( -1 );
  8906. } else if ( side === DoubleSide ) {
  8907. direction = direction.mul( faceDirection );
  8908. }
  8909. return direction;
  8910. } );
  8911. /**
  8912. * TSL object that represents the normal attribute of the current rendered object in local space.
  8913. *
  8914. * @tsl
  8915. * @type {Node<vec3>}
  8916. */
  8917. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8918. /**
  8919. * TSL object that represents the vertex normal of the current rendered object in local space.
  8920. *
  8921. * @tsl
  8922. * @type {Node<vec3>}
  8923. */
  8924. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8925. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8926. console.warn( 'THREE.TSL: Vertex attribute "normal" not found on geometry.' );
  8927. return vec3( 0, 1, 0 );
  8928. }
  8929. return normalGeometry;
  8930. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  8931. /**
  8932. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  8933. *
  8934. * @tsl
  8935. * @type {Node<vec3>}
  8936. */
  8937. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  8938. /**
  8939. * TSL object that represents the vertex normal of the current rendered object in view space.
  8940. *
  8941. * @tsl
  8942. * @type {Node<vec3>}
  8943. */
  8944. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  8945. let node;
  8946. if ( builder.material.flatShading === true ) {
  8947. node = normalFlat;
  8948. } else {
  8949. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  8950. }
  8951. return node;
  8952. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  8953. /**
  8954. * TSL object that represents the vertex normal of the current rendered object in world space.
  8955. *
  8956. * @tsl
  8957. * @type {Node<vec3>}
  8958. */
  8959. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  8960. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  8961. if ( builder.material.flatShading !== true ) {
  8962. normal = normal.toVarying( 'v_normalWorldGeometry' );
  8963. }
  8964. return normal.normalize().toVar( 'normalWorldGeometry' );
  8965. }, 'vec3' ).once() )();
  8966. /**
  8967. * TSL object that represents the vertex normal of the current rendered object in view space.
  8968. *
  8969. * @tsl
  8970. * @type {Node<vec3>}
  8971. */
  8972. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  8973. let node;
  8974. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  8975. node = normalViewGeometry;
  8976. if ( material.flatShading !== true ) {
  8977. node = directionToFaceDirection( node );
  8978. }
  8979. } else {
  8980. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8981. node = context.setupNormal().context( { getUV: null } );
  8982. }
  8983. return node;
  8984. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  8985. /**
  8986. * TSL object that represents the vertex normal of the current rendered object in world space.
  8987. *
  8988. * @tsl
  8989. * @type {Node<vec3>}
  8990. */
  8991. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  8992. /**
  8993. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  8994. *
  8995. * @tsl
  8996. * @type {Node<vec3>}
  8997. */
  8998. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  8999. let node;
  9000. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9001. node = normalView;
  9002. } else {
  9003. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9004. node = context.setupClearcoatNormal().context( { getUV: null } );
  9005. }
  9006. return node;
  9007. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9008. /**
  9009. * Transforms the normal with the given matrix.
  9010. *
  9011. * @tsl
  9012. * @function
  9013. * @param {Node<vec3>} normal - The normal.
  9014. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9015. * @return {Node<vec3>} The transformed normal.
  9016. */
  9017. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9018. const m = mat3( matrix );
  9019. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  9020. return m.mul( transformedNormal ).xyz;
  9021. } );
  9022. /**
  9023. * Transforms the given normal from local to view space.
  9024. *
  9025. * @tsl
  9026. * @function
  9027. * @param {Node<vec3>} normal - The normal.
  9028. * @param {NodeBuilder} builder - The current node builder.
  9029. * @return {Node<vec3>} The transformed normal.
  9030. */
  9031. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  9032. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  9033. if ( modelNormalViewMatrix !== null ) {
  9034. return modelNormalViewMatrix.transformDirection( normal );
  9035. }
  9036. //
  9037. const transformedNormal = modelNormalMatrix.mul( normal );
  9038. return cameraViewMatrix.transformDirection( transformedNormal );
  9039. } );
  9040. // Deprecated
  9041. /**
  9042. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  9043. *
  9044. * @tsl
  9045. * @type {Node<vec3>}
  9046. * @deprecated since r178. Use `normalView` instead.
  9047. */
  9048. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  9049. console.warn( 'THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  9050. return normalView;
  9051. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9052. /**
  9053. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  9054. *
  9055. * @tsl
  9056. * @type {Node<vec3>}
  9057. * @deprecated since r178. Use `normalWorld` instead.
  9058. */
  9059. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  9060. console.warn( 'THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  9061. return normalWorld;
  9062. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9063. /**
  9064. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  9065. *
  9066. * @tsl
  9067. * @type {Node<vec3>}
  9068. * @deprecated since r178. Use `clearcoatNormalView` instead.
  9069. */
  9070. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  9071. console.warn( 'THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  9072. return clearcoatNormalView;
  9073. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9074. const _e1$1 = /*@__PURE__*/ new Euler();
  9075. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9076. /**
  9077. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  9078. *
  9079. * @tsl
  9080. * @type {UniformNode<float>}
  9081. */
  9082. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  9083. /**
  9084. * TSL object that represents the intensity of environment maps of PBR materials.
  9085. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  9086. *
  9087. * @tsl
  9088. * @type {Node<float>}
  9089. */
  9090. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  9091. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  9092. } );
  9093. /**
  9094. * TSL object that represents the rotation of environment maps.
  9095. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  9096. * rotation of `scene.environment` instead.
  9097. *
  9098. * @tsl
  9099. * @type {Node<mat4>}
  9100. */
  9101. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  9102. return frame.material;
  9103. } ).onObjectUpdate( function ( { material, scene } ) {
  9104. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  9105. if ( rotation ) {
  9106. _e1$1.copy( rotation );
  9107. _m1$1.makeRotationFromEuler( _e1$1 );
  9108. } else {
  9109. _m1$1.identity();
  9110. }
  9111. return _m1$1;
  9112. } );
  9113. /**
  9114. * The reflect vector in view space.
  9115. *
  9116. * @tsl
  9117. * @type {Node<vec3>}
  9118. */
  9119. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  9120. /**
  9121. * The refract vector in view space.
  9122. *
  9123. * @tsl
  9124. * @type {Node<vec3>}
  9125. */
  9126. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  9127. /**
  9128. * Used for sampling cube maps when using cube reflection mapping.
  9129. *
  9130. * @tsl
  9131. * @type {Node<vec3>}
  9132. */
  9133. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9134. /**
  9135. * Used for sampling cube maps when using cube refraction mapping.
  9136. *
  9137. * @tsl
  9138. * @type {Node<vec3>}
  9139. */
  9140. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9141. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  9142. /**
  9143. * This type of uniform node represents a cube texture.
  9144. *
  9145. * @augments TextureNode
  9146. */
  9147. class CubeTextureNode extends TextureNode {
  9148. static get type() {
  9149. return 'CubeTextureNode';
  9150. }
  9151. /**
  9152. * Constructs a new cube texture node.
  9153. *
  9154. * @param {CubeTexture} value - The cube texture.
  9155. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9156. * @param {?Node<int>} [levelNode=null] - The level node.
  9157. * @param {?Node<float>} [biasNode=null] - The bias node.
  9158. */
  9159. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  9160. super( value, uvNode, levelNode, biasNode );
  9161. /**
  9162. * This flag can be used for type testing.
  9163. *
  9164. * @type {boolean}
  9165. * @readonly
  9166. * @default true
  9167. */
  9168. this.isCubeTextureNode = true;
  9169. }
  9170. /**
  9171. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  9172. *
  9173. * @param {NodeBuilder} builder - The current node builder.
  9174. * @return {string} The input type.
  9175. */
  9176. getInputType( /*builder*/ ) {
  9177. return 'cubeTexture';
  9178. }
  9179. /**
  9180. * Returns a default uvs based on the mapping type of the cube texture.
  9181. *
  9182. * @return {Node<vec3>} The default uv attribute.
  9183. */
  9184. getDefaultUV() {
  9185. const texture = this.value;
  9186. if ( texture.mapping === CubeReflectionMapping ) {
  9187. return reflectVector;
  9188. } else if ( texture.mapping === CubeRefractionMapping ) {
  9189. return refractVector;
  9190. } else {
  9191. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  9192. return vec3( 0, 0, 0 );
  9193. }
  9194. }
  9195. /**
  9196. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  9197. * for cube textures. The uv transformation matrix is not applied to cube textures.
  9198. *
  9199. * @param {boolean} value - The update toggle.
  9200. */
  9201. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  9202. /**
  9203. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  9204. * to modify the uv node for correct sampling.
  9205. *
  9206. * @param {NodeBuilder} builder - The current node builder.
  9207. * @param {Node} uvNode - The uv node to setup.
  9208. * @return {Node} The updated uv node.
  9209. */
  9210. setupUV( builder, uvNode ) {
  9211. const texture = this.value;
  9212. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  9213. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  9214. }
  9215. return materialEnvRotation.mul( uvNode );
  9216. }
  9217. /**
  9218. * Generates the uv code snippet.
  9219. *
  9220. * @param {NodeBuilder} builder - The current node builder.
  9221. * @param {Node} cubeUV - The uv node to generate code for.
  9222. * @return {string} The generated code snippet.
  9223. */
  9224. generateUV( builder, cubeUV ) {
  9225. return cubeUV.build( builder, 'vec3' );
  9226. }
  9227. }
  9228. /**
  9229. * TSL function for creating a cube texture node.
  9230. *
  9231. * @tsl
  9232. * @function
  9233. * @param {CubeTexture} value - The cube texture.
  9234. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9235. * @param {?Node<int>} [levelNode=null] - The level node.
  9236. * @param {?Node<float>} [biasNode=null] - The bias node.
  9237. * @returns {CubeTextureNode}
  9238. */
  9239. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  9240. /**
  9241. * TSL function for creating a cube texture uniform node.
  9242. *
  9243. * @tsl
  9244. * @function
  9245. * @param {?CubeTexture|CubeTextureNode} [value=EmptyTexture] - The cube texture.
  9246. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9247. * @param {?Node<int>} [levelNode=null] - The level node.
  9248. * @param {?Node<float>} [biasNode=null] - The bias node.
  9249. * @returns {CubeTextureNode}
  9250. */
  9251. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  9252. let textureNode;
  9253. if ( value && value.isCubeTextureNode === true ) {
  9254. textureNode = nodeObject( value.clone() );
  9255. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  9256. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9257. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9258. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9259. } else {
  9260. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  9261. }
  9262. return textureNode;
  9263. };
  9264. /**
  9265. * TSL function for creating a uniform cube texture node.
  9266. *
  9267. * @tsl
  9268. * @function
  9269. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  9270. * @returns {CubeTextureNode}
  9271. */
  9272. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  9273. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  9274. /**
  9275. * This class is only relevant if the referenced property is array-like.
  9276. * In this case, `ReferenceElementNode` allows to refer to a specific
  9277. * element inside the data structure via an index.
  9278. *
  9279. * @augments ArrayElementNode
  9280. */
  9281. class ReferenceElementNode extends ArrayElementNode {
  9282. static get type() {
  9283. return 'ReferenceElementNode';
  9284. }
  9285. /**
  9286. * Constructs a new reference element node.
  9287. *
  9288. * @param {?ReferenceNode} referenceNode - The reference node.
  9289. * @param {Node} indexNode - The index node that defines the element access.
  9290. */
  9291. constructor( referenceNode, indexNode ) {
  9292. super( referenceNode, indexNode );
  9293. /**
  9294. * Similar to {@link ReferenceNode#reference}, an additional
  9295. * property references to the current node.
  9296. *
  9297. * @type {?ReferenceNode}
  9298. * @default null
  9299. */
  9300. this.referenceNode = referenceNode;
  9301. /**
  9302. * This flag can be used for type testing.
  9303. *
  9304. * @type {boolean}
  9305. * @readonly
  9306. * @default true
  9307. */
  9308. this.isReferenceElementNode = true;
  9309. }
  9310. /**
  9311. * This method is overwritten since the node type is inferred from
  9312. * the uniform type of the reference node.
  9313. *
  9314. * @return {string} The node type.
  9315. */
  9316. getNodeType() {
  9317. return this.referenceNode.uniformType;
  9318. }
  9319. generate( builder ) {
  9320. const snippet = super.generate( builder );
  9321. const arrayType = this.referenceNode.getNodeType();
  9322. const elementType = this.getNodeType();
  9323. return builder.format( snippet, arrayType, elementType );
  9324. }
  9325. }
  9326. /**
  9327. * This type of node establishes a reference to a property of another object.
  9328. * In this way, the value of the node is automatically linked to the value of
  9329. * referenced object. Reference nodes internally represent the linked value
  9330. * as a uniform.
  9331. *
  9332. * @augments Node
  9333. */
  9334. class ReferenceNode extends Node {
  9335. static get type() {
  9336. return 'ReferenceNode';
  9337. }
  9338. /**
  9339. * Constructs a new reference node.
  9340. *
  9341. * @param {string} property - The name of the property the node refers to.
  9342. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  9343. * @param {?Object} [object=null] - The object the property belongs to.
  9344. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  9345. */
  9346. constructor( property, uniformType, object = null, count = null ) {
  9347. super();
  9348. /**
  9349. * The name of the property the node refers to.
  9350. *
  9351. * @type {string}
  9352. */
  9353. this.property = property;
  9354. /**
  9355. * The uniform type that should be used to represent the property value.
  9356. *
  9357. * @type {string}
  9358. */
  9359. this.uniformType = uniformType;
  9360. /**
  9361. * The object the property belongs to.
  9362. *
  9363. * @type {?Object}
  9364. * @default null
  9365. */
  9366. this.object = object;
  9367. /**
  9368. * When the linked property is an array, this parameter defines its length.
  9369. *
  9370. * @type {?number}
  9371. * @default null
  9372. */
  9373. this.count = count;
  9374. /**
  9375. * The property name might have dots so nested properties can be referred.
  9376. * The hierarchy of the names is stored inside this array.
  9377. *
  9378. * @type {Array<string>}
  9379. */
  9380. this.properties = property.split( '.' );
  9381. /**
  9382. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  9383. * since the final reference might be updated from calling code.
  9384. *
  9385. * @type {?Object}
  9386. * @default null
  9387. */
  9388. this.reference = object;
  9389. /**
  9390. * The uniform node that holds the value of the reference node.
  9391. *
  9392. * @type {UniformNode}
  9393. * @default null
  9394. */
  9395. this.node = null;
  9396. /**
  9397. * The uniform group of the internal uniform.
  9398. *
  9399. * @type {UniformGroupNode}
  9400. * @default null
  9401. */
  9402. this.group = null;
  9403. /**
  9404. * An optional label of the internal uniform node.
  9405. *
  9406. * @type {?string}
  9407. * @default null
  9408. */
  9409. this.name = null;
  9410. /**
  9411. * Overwritten since reference nodes are updated per object.
  9412. *
  9413. * @type {string}
  9414. * @default 'object'
  9415. */
  9416. this.updateType = NodeUpdateType.OBJECT;
  9417. }
  9418. /**
  9419. * When the referred property is array-like, this method can be used
  9420. * to access elements via an index node.
  9421. *
  9422. * @param {IndexNode} indexNode - indexNode.
  9423. * @return {ReferenceElementNode} A reference to an element.
  9424. */
  9425. element( indexNode ) {
  9426. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  9427. }
  9428. /**
  9429. * Sets the uniform group for this reference node.
  9430. *
  9431. * @param {UniformGroupNode} group - The uniform group to set.
  9432. * @return {ReferenceNode} A reference to this node.
  9433. */
  9434. setGroup( group ) {
  9435. this.group = group;
  9436. return this;
  9437. }
  9438. /**
  9439. * Sets the name for the internal uniform.
  9440. *
  9441. * @param {string} name - The label to set.
  9442. * @return {ReferenceNode} A reference to this node.
  9443. */
  9444. setName( name ) {
  9445. this.name = name;
  9446. return this;
  9447. }
  9448. /**
  9449. * Sets the label for the internal uniform.
  9450. *
  9451. * @deprecated
  9452. * @param {string} name - The label to set.
  9453. * @return {ReferenceNode} A reference to this node.
  9454. */
  9455. label( name ) {
  9456. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  9457. return this.setName( name );
  9458. }
  9459. /**
  9460. * Sets the node type which automatically defines the internal
  9461. * uniform type.
  9462. *
  9463. * @param {string} uniformType - The type to set.
  9464. */
  9465. setNodeType( uniformType ) {
  9466. let node = null;
  9467. if ( this.count !== null ) {
  9468. node = buffer( null, uniformType, this.count );
  9469. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  9470. node = uniformArray( null, uniformType );
  9471. } else if ( uniformType === 'texture' ) {
  9472. node = texture( null );
  9473. } else if ( uniformType === 'cubeTexture' ) {
  9474. node = cubeTexture( null );
  9475. } else {
  9476. node = uniform( null, uniformType );
  9477. }
  9478. if ( this.group !== null ) {
  9479. node.setGroup( this.group );
  9480. }
  9481. if ( this.name !== null ) node.label( this.name );
  9482. this.node = node.getSelf();
  9483. }
  9484. /**
  9485. * This method is overwritten since the node type is inferred from
  9486. * the type of the reference node.
  9487. *
  9488. * @param {NodeBuilder} builder - The current node builder.
  9489. * @return {string} The node type.
  9490. */
  9491. getNodeType( builder ) {
  9492. if ( this.node === null ) {
  9493. this.updateReference( builder );
  9494. this.updateValue();
  9495. }
  9496. return this.node.getNodeType( builder );
  9497. }
  9498. /**
  9499. * Returns the property value from the given referred object.
  9500. *
  9501. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  9502. * @return {any} The value.
  9503. */
  9504. getValueFromReference( object = this.reference ) {
  9505. const { properties } = this;
  9506. let value = object[ properties[ 0 ] ];
  9507. for ( let i = 1; i < properties.length; i ++ ) {
  9508. value = value[ properties[ i ] ];
  9509. }
  9510. return value;
  9511. }
  9512. /**
  9513. * Allows to update the reference based on the given state. The state is only
  9514. * evaluated {@link ReferenceNode#object} is not set.
  9515. *
  9516. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9517. * @return {Object} The updated reference.
  9518. */
  9519. updateReference( state ) {
  9520. this.reference = this.object !== null ? this.object : state.object;
  9521. return this.reference;
  9522. }
  9523. /**
  9524. * The output of the reference node is the internal uniform node.
  9525. *
  9526. * @param {NodeBuilder} builder - The current node builder.
  9527. * @return {UniformNode} The output node.
  9528. */
  9529. setup( /* builder */ ) {
  9530. this.updateValue();
  9531. return this.node;
  9532. }
  9533. /**
  9534. * Overwritten to update the internal uniform value.
  9535. *
  9536. * @param {NodeFrame} frame - A reference to the current node frame.
  9537. */
  9538. update( /*frame*/ ) {
  9539. this.updateValue();
  9540. }
  9541. /**
  9542. * Retrieves the value from the referred object property and uses it
  9543. * to updated the internal uniform.
  9544. */
  9545. updateValue() {
  9546. if ( this.node === null ) this.setNodeType( this.uniformType );
  9547. const value = this.getValueFromReference();
  9548. if ( Array.isArray( value ) ) {
  9549. this.node.array = value;
  9550. } else {
  9551. this.node.value = value;
  9552. }
  9553. }
  9554. }
  9555. /**
  9556. * TSL function for creating a reference node.
  9557. *
  9558. * @tsl
  9559. * @function
  9560. * @param {string} name - The name of the property the node refers to.
  9561. * @param {string} type - The uniform type that should be used to represent the property value.
  9562. * @param {?Object} [object] - The object the property belongs to.
  9563. * @returns {ReferenceNode}
  9564. */
  9565. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  9566. /**
  9567. * TSL function for creating a reference node. Use this function if you want need a reference
  9568. * to an array-like property that should be represented as a uniform buffer.
  9569. *
  9570. * @tsl
  9571. * @function
  9572. * @param {string} name - The name of the property the node refers to.
  9573. * @param {string} type - The uniform type that should be used to represent the property value.
  9574. * @param {number} count - The number of value inside the array-like object.
  9575. * @param {Object} object - An array-like object the property belongs to.
  9576. * @returns {ReferenceNode}
  9577. */
  9578. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  9579. /**
  9580. * This node is a special type of reference node which is intended
  9581. * for linking material properties with node values.
  9582. * ```js
  9583. * const opacityNode = materialReference( 'opacity', 'float', material );
  9584. * ```
  9585. * When changing `material.opacity`, the node value of `opacityNode` will
  9586. * automatically be updated.
  9587. *
  9588. * @augments ReferenceNode
  9589. */
  9590. class MaterialReferenceNode extends ReferenceNode {
  9591. static get type() {
  9592. return 'MaterialReferenceNode';
  9593. }
  9594. /**
  9595. * Constructs a new material reference node.
  9596. *
  9597. * @param {string} property - The name of the property the node refers to.
  9598. * @param {string} inputType - The uniform type that should be used to represent the property value.
  9599. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  9600. * the node refers to the material of the current rendered object.
  9601. */
  9602. constructor( property, inputType, material = null ) {
  9603. super( property, inputType, material );
  9604. /**
  9605. * The material the property belongs to. When no material is set,
  9606. * the node refers to the material of the current rendered object.
  9607. *
  9608. * @type {?Material}
  9609. * @default null
  9610. */
  9611. this.material = material;
  9612. /**
  9613. * This flag can be used for type testing.
  9614. *
  9615. * @type {boolean}
  9616. * @readonly
  9617. * @default true
  9618. */
  9619. this.isMaterialReferenceNode = true;
  9620. }
  9621. /**
  9622. * Updates the reference based on the given state. The state is only evaluated
  9623. * {@link MaterialReferenceNode#material} is not set.
  9624. *
  9625. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9626. * @return {Object} The updated reference.
  9627. */
  9628. updateReference( state ) {
  9629. this.reference = this.material !== null ? this.material : state.material;
  9630. return this.reference;
  9631. }
  9632. }
  9633. /**
  9634. * TSL function for creating a material reference node.
  9635. *
  9636. * @tsl
  9637. * @function
  9638. * @param {string} name - The name of the property the node refers to.
  9639. * @param {string} type - The uniform type that should be used to represent the property value.
  9640. * @param {?Material} [material=null] - The material the property belongs to.
  9641. * When no material is set, the node refers to the material of the current rendered object.
  9642. * @returns {MaterialReferenceNode}
  9643. */
  9644. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  9645. // Normal Mapping Without Precomputed Tangents
  9646. // http://www.thetenthplanet.de/archives/1180
  9647. const uv = uv$1();
  9648. const q0 = positionView.dFdx();
  9649. const q1 = positionView.dFdy();
  9650. const st0 = uv.dFdx();
  9651. const st1 = uv.dFdy();
  9652. const N = normalView;
  9653. const q1perp = q1.cross( N );
  9654. const q0perp = N.cross( q0 );
  9655. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  9656. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  9657. const det = T.dot( T ).max( B.dot( B ) );
  9658. const scale = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  9659. /**
  9660. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  9661. * Useful for normal mapping without precomputed tangents.
  9662. *
  9663. * Reference: http://www.thetenthplanet.de/archives/1180
  9664. *
  9665. * @tsl
  9666. * @type {Node<vec3>}
  9667. */
  9668. const tangentViewFrame = /*@__PURE__*/ T.mul( scale ).toVar( 'tangentViewFrame' );
  9669. /**
  9670. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  9671. * Complements the tangentViewFrame for constructing the tangent space basis.
  9672. *
  9673. * Reference: http://www.thetenthplanet.de/archives/1180
  9674. *
  9675. * @tsl
  9676. * @type {Node<vec3>}
  9677. */
  9678. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale ).toVar( 'bitangentViewFrame' );
  9679. /**
  9680. * TSL object that represents the tangent attribute of the current rendered object.
  9681. *
  9682. * @tsl
  9683. * @type {Node<vec4>}
  9684. */
  9685. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  9686. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  9687. builder.geometry.computeTangents();
  9688. }
  9689. return attribute( 'tangent', 'vec4' );
  9690. } )();
  9691. /**
  9692. * TSL object that represents the vertex tangent in local space of the current rendered object.
  9693. *
  9694. * @tsl
  9695. * @type {Node<vec3>}
  9696. */
  9697. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  9698. /**
  9699. * TSL object that represents the vertex tangent in view space of the current rendered object.
  9700. *
  9701. * @tsl
  9702. * @type {Node<vec3>}
  9703. */
  9704. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  9705. let node;
  9706. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  9707. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  9708. } else {
  9709. node = tangentViewFrame;
  9710. }
  9711. if ( material.flatShading !== true ) {
  9712. node = directionToFaceDirection( node );
  9713. }
  9714. return node;
  9715. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  9716. /**
  9717. * TSL object that represents the vertex tangent in world space of the current rendered object.
  9718. *
  9719. * @tsl
  9720. * @type {Node<vec3>}
  9721. */
  9722. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  9723. /**
  9724. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  9725. *
  9726. * @tsl
  9727. * @private
  9728. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  9729. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  9730. * @returns {Node<vec3>} The bitangent node.
  9731. */
  9732. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  9733. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  9734. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  9735. bitangent = bitangent.toVarying( varyingName );
  9736. }
  9737. return bitangent;
  9738. } ).once( [ 'NORMAL' ] );
  9739. /**
  9740. * TSL object that represents the bitangent attribute of the current rendered object.
  9741. *
  9742. * @tsl
  9743. * @type {Node<vec3>}
  9744. */
  9745. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  9746. /**
  9747. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  9748. *
  9749. * @tsl
  9750. * @type {Node<vec3>}
  9751. */
  9752. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  9753. /**
  9754. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  9755. *
  9756. * @tsl
  9757. * @type {Node<vec3>}
  9758. */
  9759. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  9760. let node;
  9761. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  9762. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  9763. } else {
  9764. node = bitangentViewFrame;
  9765. }
  9766. if ( material.flatShading !== true ) {
  9767. node = directionToFaceDirection( node );
  9768. }
  9769. return node;
  9770. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  9771. /**
  9772. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  9773. *
  9774. * @tsl
  9775. * @type {Node<vec3>}
  9776. */
  9777. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  9778. /**
  9779. * TSL object that represents the TBN matrix in view space.
  9780. *
  9781. * @tsl
  9782. * @type {Node<mat3>}
  9783. */
  9784. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  9785. /**
  9786. * TSL object that represents the parallax direction.
  9787. *
  9788. * @tsl
  9789. * @type {Node<mat3>}
  9790. */
  9791. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  9792. /**
  9793. * TSL function for computing parallax uv coordinates.
  9794. *
  9795. * @tsl
  9796. * @function
  9797. * @param {Node<vec2>} uv - A uv node.
  9798. * @param {Node<vec2>} scale - A scale node.
  9799. * @returns {Node<vec2>} Parallax uv coordinates.
  9800. */
  9801. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  9802. /**
  9803. * TSL function for computing bent normals.
  9804. *
  9805. * @tsl
  9806. * @function
  9807. * @returns {Node<vec3>} Bent normals.
  9808. */
  9809. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  9810. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  9811. let bentNormal = anisotropyB.cross( positionViewDirection );
  9812. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  9813. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  9814. return bentNormal;
  9815. } ).once() )();
  9816. /**
  9817. * This class can be used for applying normals maps to materials.
  9818. *
  9819. * ```js
  9820. * material.normalNode = normalMap( texture( normalTex ) );
  9821. * ```
  9822. *
  9823. * @augments TempNode
  9824. */
  9825. class NormalMapNode extends TempNode {
  9826. static get type() {
  9827. return 'NormalMapNode';
  9828. }
  9829. /**
  9830. * Constructs a new normal map node.
  9831. *
  9832. * @param {Node<vec3>} node - Represents the normal map data.
  9833. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9834. */
  9835. constructor( node, scaleNode = null ) {
  9836. super( 'vec3' );
  9837. /**
  9838. * Represents the normal map data.
  9839. *
  9840. * @type {Node<vec3>}
  9841. */
  9842. this.node = node;
  9843. /**
  9844. * Controls the intensity of the effect.
  9845. *
  9846. * @type {?Node<vec2>}
  9847. * @default null
  9848. */
  9849. this.scaleNode = scaleNode;
  9850. /**
  9851. * The normal map type.
  9852. *
  9853. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  9854. * @default TangentSpaceNormalMap
  9855. */
  9856. this.normalMapType = TangentSpaceNormalMap;
  9857. }
  9858. setup( { material } ) {
  9859. const { normalMapType, scaleNode } = this;
  9860. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  9861. if ( scaleNode !== null ) {
  9862. let scale = scaleNode;
  9863. if ( material.flatShading === true ) {
  9864. scale = directionToFaceDirection( scale );
  9865. }
  9866. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  9867. }
  9868. let output = null;
  9869. if ( normalMapType === ObjectSpaceNormalMap ) {
  9870. output = transformNormalToView( normalMap );
  9871. } else if ( normalMapType === TangentSpaceNormalMap ) {
  9872. output = TBNViewMatrix.mul( normalMap ).normalize();
  9873. } else {
  9874. console.error( `THREE.NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  9875. output = normalView; // Fallback to default normal view
  9876. }
  9877. return output;
  9878. }
  9879. }
  9880. /**
  9881. * TSL function for creating a normal map node.
  9882. *
  9883. * @tsl
  9884. * @function
  9885. * @param {Node<vec3>} node - Represents the normal map data.
  9886. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9887. * @returns {NormalMapNode}
  9888. */
  9889. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  9890. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  9891. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  9892. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  9893. // It's used to preserve the same TextureNode instance
  9894. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  9895. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  9896. return vec2(
  9897. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  9898. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  9899. ).mul( bumpScale );
  9900. } );
  9901. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9902. const perturbNormalArb = Fn( ( inputs ) => {
  9903. const { surf_pos, surf_norm, dHdxy } = inputs;
  9904. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  9905. const vSigmaX = surf_pos.dFdx().normalize();
  9906. const vSigmaY = surf_pos.dFdy().normalize();
  9907. const vN = surf_norm; // normalized
  9908. const R1 = vSigmaY.cross( vN );
  9909. const R2 = vN.cross( vSigmaX );
  9910. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  9911. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  9912. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  9913. } );
  9914. /**
  9915. * This class can be used for applying bump maps to materials.
  9916. *
  9917. * ```js
  9918. * material.normalNode = bumpMap( texture( bumpTex ) );
  9919. * ```
  9920. *
  9921. * @augments TempNode
  9922. */
  9923. class BumpMapNode extends TempNode {
  9924. static get type() {
  9925. return 'BumpMapNode';
  9926. }
  9927. /**
  9928. * Constructs a new bump map node.
  9929. *
  9930. * @param {Node<float>} textureNode - Represents the bump map data.
  9931. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9932. */
  9933. constructor( textureNode, scaleNode = null ) {
  9934. super( 'vec3' );
  9935. /**
  9936. * Represents the bump map data.
  9937. *
  9938. * @type {Node<float>}
  9939. */
  9940. this.textureNode = textureNode;
  9941. /**
  9942. * Controls the intensity of the bump effect.
  9943. *
  9944. * @type {?Node<float>}
  9945. * @default null
  9946. */
  9947. this.scaleNode = scaleNode;
  9948. }
  9949. setup() {
  9950. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  9951. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  9952. return perturbNormalArb( {
  9953. surf_pos: positionView,
  9954. surf_norm: normalView,
  9955. dHdxy
  9956. } );
  9957. }
  9958. }
  9959. /**
  9960. * TSL function for creating a bump map node.
  9961. *
  9962. * @tsl
  9963. * @function
  9964. * @param {Node<float>} textureNode - Represents the bump map data.
  9965. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9966. * @returns {BumpMapNode}
  9967. */
  9968. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  9969. const _propertyCache = new Map();
  9970. /**
  9971. * This class should simplify the node access to material properties.
  9972. * It internal uses reference nodes to make sure changes to material
  9973. * properties are automatically reflected to predefined TSL objects
  9974. * like e.g. `materialColor`.
  9975. *
  9976. * @augments Node
  9977. */
  9978. class MaterialNode extends Node {
  9979. static get type() {
  9980. return 'MaterialNode';
  9981. }
  9982. /**
  9983. * Constructs a new material node.
  9984. *
  9985. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  9986. */
  9987. constructor( scope ) {
  9988. super();
  9989. /**
  9990. * The scope defines what material property is referred by the node.
  9991. *
  9992. * @type {string}
  9993. */
  9994. this.scope = scope;
  9995. }
  9996. /**
  9997. * Returns a cached reference node for the given property and type.
  9998. *
  9999. * @param {string} property - The name of the material property.
  10000. * @param {string} type - The uniform type of the property.
  10001. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10002. */
  10003. getCache( property, type ) {
  10004. let node = _propertyCache.get( property );
  10005. if ( node === undefined ) {
  10006. node = materialReference( property, type );
  10007. _propertyCache.set( property, node );
  10008. }
  10009. return node;
  10010. }
  10011. /**
  10012. * Returns a float-typed material reference node for the given property name.
  10013. *
  10014. * @param {string} property - The name of the material property.
  10015. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10016. */
  10017. getFloat( property ) {
  10018. return this.getCache( property, 'float' );
  10019. }
  10020. /**
  10021. * Returns a color-typed material reference node for the given property name.
  10022. *
  10023. * @param {string} property - The name of the material property.
  10024. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  10025. */
  10026. getColor( property ) {
  10027. return this.getCache( property, 'color' );
  10028. }
  10029. /**
  10030. * Returns a texture-typed material reference node for the given property name.
  10031. *
  10032. * @param {string} property - The name of the material property.
  10033. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10034. */
  10035. getTexture( property ) {
  10036. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  10037. }
  10038. /**
  10039. * The node setup is done depending on the selected scope. Multiple material properties
  10040. * might be grouped into a single node composition if they logically belong together.
  10041. *
  10042. * @param {NodeBuilder} builder - The current node builder.
  10043. * @return {Node} The node representing the selected scope.
  10044. */
  10045. setup( builder ) {
  10046. const material = builder.context.material;
  10047. const scope = this.scope;
  10048. let node = null;
  10049. if ( scope === MaterialNode.COLOR ) {
  10050. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  10051. if ( material.map && material.map.isTexture === true ) {
  10052. node = colorNode.mul( this.getTexture( 'map' ) );
  10053. } else {
  10054. node = colorNode;
  10055. }
  10056. } else if ( scope === MaterialNode.OPACITY ) {
  10057. const opacityNode = this.getFloat( scope );
  10058. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  10059. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  10060. } else {
  10061. node = opacityNode;
  10062. }
  10063. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  10064. if ( material.specularMap && material.specularMap.isTexture === true ) {
  10065. node = this.getTexture( 'specular' ).r;
  10066. } else {
  10067. node = float( 1 );
  10068. }
  10069. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  10070. const specularIntensityNode = this.getFloat( scope );
  10071. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  10072. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  10073. } else {
  10074. node = specularIntensityNode;
  10075. }
  10076. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  10077. const specularColorNode = this.getColor( scope );
  10078. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  10079. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  10080. } else {
  10081. node = specularColorNode;
  10082. }
  10083. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  10084. const roughnessNode = this.getFloat( scope );
  10085. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  10086. node = roughnessNode.mul( this.getTexture( scope ).g );
  10087. } else {
  10088. node = roughnessNode;
  10089. }
  10090. } else if ( scope === MaterialNode.METALNESS ) {
  10091. const metalnessNode = this.getFloat( scope );
  10092. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  10093. node = metalnessNode.mul( this.getTexture( scope ).b );
  10094. } else {
  10095. node = metalnessNode;
  10096. }
  10097. } else if ( scope === MaterialNode.EMISSIVE ) {
  10098. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  10099. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  10100. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  10101. node = emissiveNode.mul( this.getTexture( scope ) );
  10102. } else {
  10103. node = emissiveNode;
  10104. }
  10105. } else if ( scope === MaterialNode.NORMAL ) {
  10106. if ( material.normalMap ) {
  10107. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  10108. node.normalMapType = material.normalMapType;
  10109. } else if ( material.bumpMap ) {
  10110. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  10111. } else {
  10112. node = normalView;
  10113. }
  10114. } else if ( scope === MaterialNode.CLEARCOAT ) {
  10115. const clearcoatNode = this.getFloat( scope );
  10116. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  10117. node = clearcoatNode.mul( this.getTexture( scope ).r );
  10118. } else {
  10119. node = clearcoatNode;
  10120. }
  10121. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  10122. const clearcoatRoughnessNode = this.getFloat( scope );
  10123. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  10124. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  10125. } else {
  10126. node = clearcoatRoughnessNode;
  10127. }
  10128. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  10129. if ( material.clearcoatNormalMap ) {
  10130. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  10131. } else {
  10132. node = normalView;
  10133. }
  10134. } else if ( scope === MaterialNode.SHEEN ) {
  10135. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  10136. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  10137. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  10138. } else {
  10139. node = sheenNode;
  10140. }
  10141. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  10142. const sheenRoughnessNode = this.getFloat( scope );
  10143. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  10144. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  10145. } else {
  10146. node = sheenRoughnessNode;
  10147. }
  10148. node = node.clamp( 0.07, 1.0 );
  10149. } else if ( scope === MaterialNode.ANISOTROPY ) {
  10150. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  10151. const anisotropyPolar = this.getTexture( scope );
  10152. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  10153. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  10154. } else {
  10155. node = materialAnisotropyVector;
  10156. }
  10157. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  10158. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  10159. if ( material.iridescenceThicknessMap ) {
  10160. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  10161. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  10162. } else {
  10163. node = iridescenceThicknessMaximum;
  10164. }
  10165. } else if ( scope === MaterialNode.TRANSMISSION ) {
  10166. const transmissionNode = this.getFloat( scope );
  10167. if ( material.transmissionMap ) {
  10168. node = transmissionNode.mul( this.getTexture( scope ).r );
  10169. } else {
  10170. node = transmissionNode;
  10171. }
  10172. } else if ( scope === MaterialNode.THICKNESS ) {
  10173. const thicknessNode = this.getFloat( scope );
  10174. if ( material.thicknessMap ) {
  10175. node = thicknessNode.mul( this.getTexture( scope ).g );
  10176. } else {
  10177. node = thicknessNode;
  10178. }
  10179. } else if ( scope === MaterialNode.IOR ) {
  10180. node = this.getFloat( scope );
  10181. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  10182. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  10183. } else if ( scope === MaterialNode.AO ) {
  10184. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  10185. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  10186. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  10187. } else {
  10188. const outputType = this.getNodeType( builder );
  10189. node = this.getCache( scope, outputType );
  10190. }
  10191. return node;
  10192. }
  10193. }
  10194. MaterialNode.ALPHA_TEST = 'alphaTest';
  10195. MaterialNode.COLOR = 'color';
  10196. MaterialNode.OPACITY = 'opacity';
  10197. MaterialNode.SHININESS = 'shininess';
  10198. MaterialNode.SPECULAR = 'specular';
  10199. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  10200. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  10201. MaterialNode.SPECULAR_COLOR = 'specularColor';
  10202. MaterialNode.REFLECTIVITY = 'reflectivity';
  10203. MaterialNode.ROUGHNESS = 'roughness';
  10204. MaterialNode.METALNESS = 'metalness';
  10205. MaterialNode.NORMAL = 'normal';
  10206. MaterialNode.CLEARCOAT = 'clearcoat';
  10207. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  10208. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  10209. MaterialNode.EMISSIVE = 'emissive';
  10210. MaterialNode.ROTATION = 'rotation';
  10211. MaterialNode.SHEEN = 'sheen';
  10212. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  10213. MaterialNode.ANISOTROPY = 'anisotropy';
  10214. MaterialNode.IRIDESCENCE = 'iridescence';
  10215. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  10216. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  10217. MaterialNode.IOR = 'ior';
  10218. MaterialNode.TRANSMISSION = 'transmission';
  10219. MaterialNode.THICKNESS = 'thickness';
  10220. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  10221. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  10222. MaterialNode.LINE_SCALE = 'scale';
  10223. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  10224. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  10225. MaterialNode.LINE_WIDTH = 'linewidth';
  10226. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  10227. MaterialNode.POINT_SIZE = 'size';
  10228. MaterialNode.DISPERSION = 'dispersion';
  10229. MaterialNode.LIGHT_MAP = 'light';
  10230. MaterialNode.AO = 'ao';
  10231. /**
  10232. * TSL object that represents alpha test of the current material.
  10233. *
  10234. * @tsl
  10235. * @type {Node<float>}
  10236. */
  10237. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  10238. /**
  10239. * TSL object that represents the diffuse color of the current material.
  10240. * The value is composed via `color` * `map`.
  10241. *
  10242. * @tsl
  10243. * @type {Node<vec3>}
  10244. */
  10245. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  10246. /**
  10247. * TSL object that represents the shininess of the current material.
  10248. *
  10249. * @tsl
  10250. * @type {Node<float>}
  10251. */
  10252. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  10253. /**
  10254. * TSL object that represents the emissive color of the current material.
  10255. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  10256. *
  10257. * @tsl
  10258. * @type {Node<vec3>}
  10259. */
  10260. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  10261. /**
  10262. * TSL object that represents the opacity of the current material.
  10263. * The value is composed via `opacity` * `alphaMap`.
  10264. *
  10265. * @tsl
  10266. * @type {Node<float>}
  10267. */
  10268. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  10269. /**
  10270. * TSL object that represents the specular of the current material.
  10271. *
  10272. * @tsl
  10273. * @type {Node<vec3>}
  10274. */
  10275. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  10276. /**
  10277. * TSL object that represents the specular intensity of the current material.
  10278. * The value is composed via `specularIntensity` * `specularMap.a`.
  10279. *
  10280. * @tsl
  10281. * @type {Node<float>}
  10282. */
  10283. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  10284. /**
  10285. * TSL object that represents the specular color of the current material.
  10286. * The value is composed via `specularColor` * `specularMap.rgb`.
  10287. *
  10288. * @tsl
  10289. * @type {Node<vec3>}
  10290. */
  10291. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  10292. /**
  10293. * TSL object that represents the specular strength of the current material.
  10294. * The value is composed via `specularMap.r`.
  10295. *
  10296. * @tsl
  10297. * @type {Node<float>}
  10298. */
  10299. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  10300. /**
  10301. * TSL object that represents the reflectivity of the current material.
  10302. *
  10303. * @tsl
  10304. * @type {Node<float>}
  10305. */
  10306. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  10307. /**
  10308. * TSL object that represents the roughness of the current material.
  10309. * The value is composed via `roughness` * `roughnessMap.g`.
  10310. *
  10311. * @tsl
  10312. * @type {Node<float>}
  10313. */
  10314. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  10315. /**
  10316. * TSL object that represents the metalness of the current material.
  10317. * The value is composed via `metalness` * `metalnessMap.b`.
  10318. *
  10319. * @tsl
  10320. * @type {Node<float>}
  10321. */
  10322. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  10323. /**
  10324. * TSL object that represents the normal of the current material.
  10325. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  10326. *
  10327. * @tsl
  10328. * @type {Node<vec3>}
  10329. */
  10330. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  10331. /**
  10332. * TSL object that represents the clearcoat of the current material.
  10333. * The value is composed via `clearcoat` * `clearcoatMap.r`
  10334. *
  10335. * @tsl
  10336. * @type {Node<float>}
  10337. */
  10338. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  10339. /**
  10340. * TSL object that represents the clearcoat roughness of the current material.
  10341. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  10342. *
  10343. * @tsl
  10344. * @type {Node<float>}
  10345. */
  10346. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  10347. /**
  10348. * TSL object that represents the clearcoat normal of the current material.
  10349. * The value will be either `clearcoatNormalMap` or `normalView`.
  10350. *
  10351. * @tsl
  10352. * @type {Node<vec3>}
  10353. */
  10354. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  10355. /**
  10356. * TSL object that represents the rotation of the current sprite material.
  10357. *
  10358. * @tsl
  10359. * @type {Node<float>}
  10360. */
  10361. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  10362. /**
  10363. * TSL object that represents the sheen color of the current material.
  10364. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  10365. *
  10366. * @tsl
  10367. * @type {Node<vec3>}
  10368. */
  10369. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  10370. /**
  10371. * TSL object that represents the sheen roughness of the current material.
  10372. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  10373. *
  10374. * @tsl
  10375. * @type {Node<float>}
  10376. */
  10377. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  10378. /**
  10379. * TSL object that represents the anisotropy of the current material.
  10380. *
  10381. * @tsl
  10382. * @type {Node<vec2>}
  10383. */
  10384. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  10385. /**
  10386. * TSL object that represents the iridescence of the current material.
  10387. *
  10388. * @tsl
  10389. * @type {Node<float>}
  10390. */
  10391. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  10392. /**
  10393. * TSL object that represents the iridescence IOR of the current material.
  10394. *
  10395. * @tsl
  10396. * @type {Node<float>}
  10397. */
  10398. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  10399. /**
  10400. * TSL object that represents the iridescence thickness of the current material.
  10401. *
  10402. * @tsl
  10403. * @type {Node<float>}
  10404. */
  10405. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  10406. /**
  10407. * TSL object that represents the transmission of the current material.
  10408. * The value is composed via `transmission` * `transmissionMap.r`.
  10409. *
  10410. * @tsl
  10411. * @type {Node<float>}
  10412. */
  10413. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  10414. /**
  10415. * TSL object that represents the thickness of the current material.
  10416. * The value is composed via `thickness` * `thicknessMap.g`.
  10417. *
  10418. * @tsl
  10419. * @type {Node<float>}
  10420. */
  10421. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  10422. /**
  10423. * TSL object that represents the IOR of the current material.
  10424. *
  10425. * @tsl
  10426. * @type {Node<float>}
  10427. */
  10428. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  10429. /**
  10430. * TSL object that represents the attenuation distance of the current material.
  10431. *
  10432. * @tsl
  10433. * @type {Node<float>}
  10434. */
  10435. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  10436. /**
  10437. * TSL object that represents the attenuation color of the current material.
  10438. *
  10439. * @tsl
  10440. * @type {Node<vec3>}
  10441. */
  10442. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  10443. /**
  10444. * TSL object that represents the scale of the current dashed line material.
  10445. *
  10446. * @tsl
  10447. * @type {Node<float>}
  10448. */
  10449. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  10450. /**
  10451. * TSL object that represents the dash size of the current dashed line material.
  10452. *
  10453. * @tsl
  10454. * @type {Node<float>}
  10455. */
  10456. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  10457. /**
  10458. * TSL object that represents the gap size of the current dashed line material.
  10459. *
  10460. * @tsl
  10461. * @type {Node<float>}
  10462. */
  10463. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  10464. /**
  10465. * TSL object that represents the line width of the current line material.
  10466. *
  10467. * @tsl
  10468. * @type {Node<float>}
  10469. */
  10470. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  10471. /**
  10472. * TSL object that represents the dash offset of the current line material.
  10473. *
  10474. * @tsl
  10475. * @type {Node<float>}
  10476. */
  10477. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  10478. /**
  10479. * TSL object that represents the point size of the current points material.
  10480. *
  10481. * @tsl
  10482. * @type {Node<float>}
  10483. */
  10484. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  10485. /**
  10486. * TSL object that represents the dispersion of the current material.
  10487. *
  10488. * @tsl
  10489. * @type {Node<float>}
  10490. */
  10491. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  10492. /**
  10493. * TSL object that represents the light map of the current material.
  10494. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  10495. *
  10496. * @tsl
  10497. * @type {Node<vec3>}
  10498. */
  10499. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  10500. /**
  10501. * TSL object that represents the ambient occlusion map of the current material.
  10502. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  10503. *
  10504. * @tsl
  10505. * @type {Node<float>}
  10506. */
  10507. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  10508. /**
  10509. * TSL object that represents the anisotropy vector of the current material.
  10510. *
  10511. * @tsl
  10512. * @type {Node<vec2>}
  10513. */
  10514. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  10515. return frame.material;
  10516. } ).onRenderUpdate( function ( { material } ) {
  10517. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  10518. } );
  10519. /**
  10520. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  10521. *
  10522. * @tsl
  10523. * @type {VaryingNode<vec4>}
  10524. */
  10525. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10526. return builder.context.setupModelViewProjection();
  10527. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  10528. /**
  10529. * This class represents shader indices of different types. The following predefined node
  10530. * objects cover frequent use cases:
  10531. *
  10532. * - `vertexIndex`: The index of a vertex within a mesh.
  10533. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  10534. * - `drawIndex`: The index of a draw call.
  10535. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  10536. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  10537. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  10538. *
  10539. * @augments Node
  10540. */
  10541. class IndexNode extends Node {
  10542. static get type() {
  10543. return 'IndexNode';
  10544. }
  10545. /**
  10546. * Constructs a new index node.
  10547. *
  10548. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  10549. */
  10550. constructor( scope ) {
  10551. super( 'uint' );
  10552. /**
  10553. * The scope of the index node.
  10554. *
  10555. * @type {string}
  10556. */
  10557. this.scope = scope;
  10558. /**
  10559. * This flag can be used for type testing.
  10560. *
  10561. * @type {boolean}
  10562. * @readonly
  10563. * @default true
  10564. */
  10565. this.isIndexNode = true;
  10566. }
  10567. generate( builder ) {
  10568. const nodeType = this.getNodeType( builder );
  10569. const scope = this.scope;
  10570. let propertyName;
  10571. if ( scope === IndexNode.VERTEX ) {
  10572. propertyName = builder.getVertexIndex();
  10573. } else if ( scope === IndexNode.INSTANCE ) {
  10574. propertyName = builder.getInstanceIndex();
  10575. } else if ( scope === IndexNode.DRAW ) {
  10576. propertyName = builder.getDrawIndex();
  10577. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  10578. propertyName = builder.getInvocationLocalIndex();
  10579. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  10580. propertyName = builder.getInvocationSubgroupIndex();
  10581. } else if ( scope === IndexNode.SUBGROUP ) {
  10582. propertyName = builder.getSubgroupIndex();
  10583. } else {
  10584. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  10585. }
  10586. let output;
  10587. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  10588. output = propertyName;
  10589. } else {
  10590. const nodeVarying = varying( this );
  10591. output = nodeVarying.build( builder, nodeType );
  10592. }
  10593. return output;
  10594. }
  10595. }
  10596. IndexNode.VERTEX = 'vertex';
  10597. IndexNode.INSTANCE = 'instance';
  10598. IndexNode.SUBGROUP = 'subgroup';
  10599. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  10600. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  10601. IndexNode.DRAW = 'draw';
  10602. /**
  10603. * TSL object that represents the index of a vertex within a mesh.
  10604. *
  10605. * @tsl
  10606. * @type {IndexNode}
  10607. */
  10608. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  10609. /**
  10610. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  10611. *
  10612. * @tsl
  10613. * @type {IndexNode}
  10614. */
  10615. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  10616. /**
  10617. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  10618. *
  10619. * @tsl
  10620. * @type {IndexNode}
  10621. */
  10622. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  10623. /**
  10624. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  10625. *
  10626. * @tsl
  10627. * @type {IndexNode}
  10628. */
  10629. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  10630. /**
  10631. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  10632. *
  10633. * @tsl
  10634. * @type {IndexNode}
  10635. */
  10636. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  10637. /**
  10638. * TSL object that represents the index of a draw call.
  10639. *
  10640. * @tsl
  10641. * @type {IndexNode}
  10642. */
  10643. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  10644. /**
  10645. * This node implements the vertex shader logic which is required
  10646. * when rendering 3D objects via instancing. The code makes sure
  10647. * vertex positions, normals and colors can be modified via instanced
  10648. * data.
  10649. *
  10650. * @augments Node
  10651. */
  10652. class InstanceNode extends Node {
  10653. static get type() {
  10654. return 'InstanceNode';
  10655. }
  10656. /**
  10657. * Constructs a new instance node.
  10658. *
  10659. * @param {number} count - The number of instances.
  10660. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10661. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10662. */
  10663. constructor( count, instanceMatrix, instanceColor = null ) {
  10664. super( 'void' );
  10665. /**
  10666. * The number of instances.
  10667. *
  10668. * @type {number}
  10669. */
  10670. this.count = count;
  10671. /**
  10672. * Instanced buffer attribute representing the transformation of instances.
  10673. *
  10674. * @type {InstancedBufferAttribute}
  10675. */
  10676. this.instanceMatrix = instanceMatrix;
  10677. /**
  10678. * Instanced buffer attribute representing the color of instances.
  10679. *
  10680. * @type {InstancedBufferAttribute}
  10681. */
  10682. this.instanceColor = instanceColor;
  10683. /**
  10684. * The node that represents the instance matrix data.
  10685. *
  10686. * @type {?Node}
  10687. */
  10688. this.instanceMatrixNode = null;
  10689. /**
  10690. * The node that represents the instance color data.
  10691. *
  10692. * @type {?Node}
  10693. * @default null
  10694. */
  10695. this.instanceColorNode = null;
  10696. /**
  10697. * The update type is set to `frame` since an update
  10698. * of instanced buffer data must be checked per frame.
  10699. *
  10700. * @type {string}
  10701. * @default 'frame'
  10702. */
  10703. this.updateType = NodeUpdateType.FRAME;
  10704. /**
  10705. * A reference to a buffer that is used by `instanceMatrixNode`.
  10706. *
  10707. * @type {?InstancedInterleavedBuffer}
  10708. */
  10709. this.buffer = null;
  10710. /**
  10711. * A reference to a buffer that is used by `instanceColorNode`.
  10712. *
  10713. * @type {?InstancedBufferAttribute}
  10714. */
  10715. this.bufferColor = null;
  10716. }
  10717. /**
  10718. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10719. * to predefined node variables for accumulation. That follows the same patterns
  10720. * like with morph and skinning nodes.
  10721. *
  10722. * @param {NodeBuilder} builder - The current node builder.
  10723. */
  10724. setup( builder ) {
  10725. const { count, instanceMatrix, instanceColor } = this;
  10726. let { instanceMatrixNode, instanceColorNode } = this;
  10727. if ( instanceMatrixNode === null ) {
  10728. // 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.
  10729. if ( count <= 1000 ) {
  10730. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  10731. } else {
  10732. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  10733. this.buffer = buffer;
  10734. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10735. const instanceBuffers = [
  10736. // F.Signature -> bufferAttribute( array, type, stride, offset )
  10737. bufferFn( buffer, 'vec4', 16, 0 ),
  10738. bufferFn( buffer, 'vec4', 16, 4 ),
  10739. bufferFn( buffer, 'vec4', 16, 8 ),
  10740. bufferFn( buffer, 'vec4', 16, 12 )
  10741. ];
  10742. instanceMatrixNode = mat4( ...instanceBuffers );
  10743. }
  10744. this.instanceMatrixNode = instanceMatrixNode;
  10745. }
  10746. if ( instanceColor && instanceColorNode === null ) {
  10747. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  10748. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10749. this.bufferColor = buffer;
  10750. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  10751. this.instanceColorNode = instanceColorNode;
  10752. }
  10753. // POSITION
  10754. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  10755. positionLocal.assign( instancePosition );
  10756. // NORMAL
  10757. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10758. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  10759. // ASSIGNS
  10760. normalLocal.assign( instanceNormal );
  10761. }
  10762. // COLOR
  10763. if ( this.instanceColorNode !== null ) {
  10764. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  10765. }
  10766. }
  10767. /**
  10768. * Checks if the internal buffers required an update.
  10769. *
  10770. * @param {NodeFrame} frame - The current node frame.
  10771. */
  10772. update( /*frame*/ ) {
  10773. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  10774. this.buffer.version = this.instanceMatrix.version;
  10775. }
  10776. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  10777. this.bufferColor.version = this.instanceColor.version;
  10778. }
  10779. }
  10780. }
  10781. /**
  10782. * TSL function for creating an instance node.
  10783. *
  10784. * @tsl
  10785. * @function
  10786. * @param {number} count - The number of instances.
  10787. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10788. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10789. * @returns {InstanceNode}
  10790. */
  10791. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  10792. /**
  10793. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  10794. * It allows an easier setup of the instance node.
  10795. *
  10796. * @augments InstanceNode
  10797. */
  10798. class InstancedMeshNode extends InstanceNode {
  10799. static get type() {
  10800. return 'InstancedMeshNode';
  10801. }
  10802. /**
  10803. * Constructs a new instanced mesh node.
  10804. *
  10805. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  10806. */
  10807. constructor( instancedMesh ) {
  10808. const { count, instanceMatrix, instanceColor } = instancedMesh;
  10809. super( count, instanceMatrix, instanceColor );
  10810. /**
  10811. * A reference to the instanced mesh.
  10812. *
  10813. * @type {InstancedMesh}
  10814. */
  10815. this.instancedMesh = instancedMesh;
  10816. }
  10817. }
  10818. /**
  10819. * TSL function for creating an instanced mesh node.
  10820. *
  10821. * @tsl
  10822. * @function
  10823. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  10824. * @returns {InstancedMeshNode}
  10825. */
  10826. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  10827. /**
  10828. * This node implements the vertex shader logic which is required
  10829. * when rendering 3D objects via batching. `BatchNode` must be used
  10830. * with instances of {@link BatchedMesh}.
  10831. *
  10832. * @augments Node
  10833. */
  10834. class BatchNode extends Node {
  10835. static get type() {
  10836. return 'BatchNode';
  10837. }
  10838. /**
  10839. * Constructs a new batch node.
  10840. *
  10841. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10842. */
  10843. constructor( batchMesh ) {
  10844. super( 'void' );
  10845. /**
  10846. * A reference to batched mesh.
  10847. *
  10848. * @type {BatchedMesh}
  10849. */
  10850. this.batchMesh = batchMesh;
  10851. /**
  10852. * The batching index node.
  10853. *
  10854. * @type {?IndexNode}
  10855. * @default null
  10856. */
  10857. this.batchingIdNode = null;
  10858. }
  10859. /**
  10860. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10861. * to predefined node variables for accumulation. That follows the same patterns
  10862. * like with morph and skinning nodes.
  10863. *
  10864. * @param {NodeBuilder} builder - The current node builder.
  10865. */
  10866. setup( builder ) {
  10867. if ( this.batchingIdNode === null ) {
  10868. if ( builder.getDrawIndex() === null ) {
  10869. this.batchingIdNode = instanceIndex;
  10870. } else {
  10871. this.batchingIdNode = drawIndex;
  10872. }
  10873. }
  10874. const getIndirectIndex = Fn( ( [ id ] ) => {
  10875. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  10876. const x = int( id ).mod( size );
  10877. const y = int( id ).div( size );
  10878. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  10879. } ).setLayout( {
  10880. name: 'getIndirectIndex',
  10881. type: 'uint',
  10882. inputs: [
  10883. { name: 'id', type: 'int' }
  10884. ]
  10885. } );
  10886. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  10887. const matricesTexture = this.batchMesh._matricesTexture;
  10888. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  10889. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  10890. const x = j.mod( size );
  10891. const y = j.div( size );
  10892. const batchingMatrix = mat4(
  10893. textureLoad( matricesTexture, ivec2( x, y ) ),
  10894. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  10895. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  10896. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  10897. );
  10898. const colorsTexture = this.batchMesh._colorsTexture;
  10899. if ( colorsTexture !== null ) {
  10900. const getBatchingColor = Fn( ( [ id ] ) => {
  10901. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  10902. const j = id;
  10903. const x = j.mod( size );
  10904. const y = j.div( size );
  10905. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  10906. } ).setLayout( {
  10907. name: 'getBatchingColor',
  10908. type: 'vec3',
  10909. inputs: [
  10910. { name: 'id', type: 'int' }
  10911. ]
  10912. } );
  10913. const color = getBatchingColor( indirectId );
  10914. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  10915. }
  10916. const bm = mat3( batchingMatrix );
  10917. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  10918. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  10919. const batchingNormal = bm.mul( transformedNormal ).xyz;
  10920. normalLocal.assign( batchingNormal );
  10921. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10922. tangentLocal.mulAssign( bm );
  10923. }
  10924. }
  10925. }
  10926. /**
  10927. * TSL function for creating a batch node.
  10928. *
  10929. * @tsl
  10930. * @function
  10931. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10932. * @returns {BatchNode}
  10933. */
  10934. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  10935. /**
  10936. * This class enables element access on instances of {@link StorageBufferNode}.
  10937. * In most cases, it is indirectly used when accessing elements with the
  10938. * {@link StorageBufferNode#element} method.
  10939. *
  10940. * ```js
  10941. * const position = positionStorage.element( instanceIndex );
  10942. * ```
  10943. *
  10944. * @augments ArrayElementNode
  10945. */
  10946. class StorageArrayElementNode extends ArrayElementNode {
  10947. static get type() {
  10948. return 'StorageArrayElementNode';
  10949. }
  10950. /**
  10951. * Constructs storage buffer element node.
  10952. *
  10953. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10954. * @param {Node} indexNode - The index node that defines the element access.
  10955. */
  10956. constructor( storageBufferNode, indexNode ) {
  10957. super( storageBufferNode, indexNode );
  10958. /**
  10959. * This flag can be used for type testing.
  10960. *
  10961. * @type {boolean}
  10962. * @readonly
  10963. * @default true
  10964. */
  10965. this.isStorageArrayElementNode = true;
  10966. }
  10967. /**
  10968. * The storage buffer node.
  10969. *
  10970. * @param {Node} value
  10971. * @type {StorageBufferNode}
  10972. */
  10973. set storageBufferNode( value ) {
  10974. this.node = value;
  10975. }
  10976. get storageBufferNode() {
  10977. return this.node;
  10978. }
  10979. getMemberType( builder, name ) {
  10980. const structTypeNode = this.storageBufferNode.structTypeNode;
  10981. if ( structTypeNode ) {
  10982. return structTypeNode.getMemberType( builder, name );
  10983. }
  10984. return 'void';
  10985. }
  10986. setup( builder ) {
  10987. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10988. if ( this.node.isPBO === true ) {
  10989. builder.setupPBO( this.node );
  10990. }
  10991. }
  10992. return super.setup( builder );
  10993. }
  10994. generate( builder, output ) {
  10995. let snippet;
  10996. const isAssignContext = builder.context.assign;
  10997. //
  10998. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10999. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11000. snippet = builder.generatePBO( this );
  11001. } else {
  11002. snippet = this.node.build( builder );
  11003. }
  11004. } else {
  11005. snippet = super.generate( builder );
  11006. }
  11007. if ( isAssignContext !== true ) {
  11008. const type = this.getNodeType( builder );
  11009. snippet = builder.format( snippet, type, output );
  11010. }
  11011. return snippet;
  11012. }
  11013. }
  11014. /**
  11015. * TSL function for creating a storage element node.
  11016. *
  11017. * @tsl
  11018. * @function
  11019. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11020. * @param {Node} indexNode - The index node that defines the element access.
  11021. * @returns {StorageArrayElementNode}
  11022. */
  11023. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11024. /**
  11025. * This node is used in context of compute shaders and allows to define a
  11026. * storage buffer for data. A typical workflow is to create instances of
  11027. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11028. * setup up a compute shader that writes into the buffers and then convert
  11029. * the storage buffers to attribute nodes for rendering.
  11030. *
  11031. * ```js
  11032. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11033. *
  11034. * const computeInit = Fn( () => { // the compute shader
  11035. *
  11036. * const position = positionBuffer.element( instanceIndex );
  11037. *
  11038. * // compute position data
  11039. *
  11040. * position.x = 1;
  11041. * position.y = 1;
  11042. * position.z = 1;
  11043. *
  11044. * } )().compute( particleCount );
  11045. *
  11046. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11047. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11048. *
  11049. * renderer.computeAsync( computeInit );
  11050. *
  11051. * ```
  11052. *
  11053. * @augments BufferNode
  11054. */
  11055. class StorageBufferNode extends BufferNode {
  11056. static get type() {
  11057. return 'StorageBufferNode';
  11058. }
  11059. /**
  11060. * Constructs a new storage buffer node.
  11061. *
  11062. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11063. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11064. * @param {number} [bufferCount=0] - The buffer count.
  11065. */
  11066. constructor( value, bufferType = null, bufferCount = 0 ) {
  11067. let nodeType, structTypeNode = null;
  11068. if ( bufferType && bufferType.isStruct ) {
  11069. nodeType = 'struct';
  11070. structTypeNode = bufferType.layout;
  11071. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11072. bufferCount = value.count;
  11073. }
  11074. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11075. nodeType = getTypeFromLength( value.itemSize );
  11076. bufferCount = value.count;
  11077. } else {
  11078. nodeType = bufferType;
  11079. }
  11080. super( value, nodeType, bufferCount );
  11081. /**
  11082. * This flag can be used for type testing.
  11083. *
  11084. * @type {boolean}
  11085. * @readonly
  11086. * @default true
  11087. */
  11088. this.isStorageBufferNode = true;
  11089. /**
  11090. * The buffer struct type.
  11091. *
  11092. * @type {?StructTypeNode}
  11093. * @default null
  11094. */
  11095. this.structTypeNode = structTypeNode;
  11096. /**
  11097. * The access type of the texture node.
  11098. *
  11099. * @type {string}
  11100. * @default 'readWrite'
  11101. */
  11102. this.access = NodeAccess.READ_WRITE;
  11103. /**
  11104. * Whether the node is atomic or not.
  11105. *
  11106. * @type {boolean}
  11107. * @default false
  11108. */
  11109. this.isAtomic = false;
  11110. /**
  11111. * Whether the node represents a PBO or not.
  11112. * Only relevant for WebGL.
  11113. *
  11114. * @type {boolean}
  11115. * @default false
  11116. */
  11117. this.isPBO = false;
  11118. /**
  11119. * A reference to the internal buffer attribute node.
  11120. *
  11121. * @type {?BufferAttributeNode}
  11122. * @default null
  11123. */
  11124. this._attribute = null;
  11125. /**
  11126. * A reference to the internal varying node.
  11127. *
  11128. * @type {?VaryingNode}
  11129. * @default null
  11130. */
  11131. this._varying = null;
  11132. /**
  11133. * `StorageBufferNode` sets this property to `true` by default.
  11134. *
  11135. * @type {boolean}
  11136. * @default true
  11137. */
  11138. this.global = true;
  11139. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11140. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11141. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11142. else value.isStorageBufferAttribute = true;
  11143. }
  11144. }
  11145. /**
  11146. * This method is overwritten since the buffer data might be shared
  11147. * and thus the hash should be shared as well.
  11148. *
  11149. * @param {NodeBuilder} builder - The current node builder.
  11150. * @return {string} The hash.
  11151. */
  11152. getHash( builder ) {
  11153. if ( this.bufferCount === 0 ) {
  11154. let bufferData = builder.globalCache.getData( this.value );
  11155. if ( bufferData === undefined ) {
  11156. bufferData = {
  11157. node: this
  11158. };
  11159. builder.globalCache.setData( this.value, bufferData );
  11160. }
  11161. return bufferData.node.uuid;
  11162. }
  11163. return this.uuid;
  11164. }
  11165. /**
  11166. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11167. *
  11168. * @param {NodeBuilder} builder - The current node builder.
  11169. * @return {string} The input type.
  11170. */
  11171. getInputType( /*builder*/ ) {
  11172. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11173. }
  11174. /**
  11175. * Enables element access with the given index node.
  11176. *
  11177. * @param {IndexNode} indexNode - The index node.
  11178. * @return {StorageArrayElementNode} A node representing the element access.
  11179. */
  11180. element( indexNode ) {
  11181. return storageElement( this, indexNode );
  11182. }
  11183. /**
  11184. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11185. *
  11186. * @param {boolean} value - The value so set.
  11187. * @return {StorageBufferNode} A reference to this node.
  11188. */
  11189. setPBO( value ) {
  11190. this.isPBO = value;
  11191. return this;
  11192. }
  11193. /**
  11194. * Returns the `isPBO` value.
  11195. *
  11196. * @return {boolean} Whether the node represents a PBO or not.
  11197. */
  11198. getPBO() {
  11199. return this.isPBO;
  11200. }
  11201. /**
  11202. * Defines the node access.
  11203. *
  11204. * @param {string} value - The node access.
  11205. * @return {StorageBufferNode} A reference to this node.
  11206. */
  11207. setAccess( value ) {
  11208. this.access = value;
  11209. return this;
  11210. }
  11211. /**
  11212. * Convenience method for configuring a read-only node access.
  11213. *
  11214. * @return {StorageBufferNode} A reference to this node.
  11215. */
  11216. toReadOnly() {
  11217. return this.setAccess( NodeAccess.READ_ONLY );
  11218. }
  11219. /**
  11220. * Defines whether the node is atomic or not.
  11221. *
  11222. * @param {boolean} value - The atomic flag.
  11223. * @return {StorageBufferNode} A reference to this node.
  11224. */
  11225. setAtomic( value ) {
  11226. this.isAtomic = value;
  11227. return this;
  11228. }
  11229. /**
  11230. * Convenience method for making this node atomic.
  11231. *
  11232. * @return {StorageBufferNode} A reference to this node.
  11233. */
  11234. toAtomic() {
  11235. return this.setAtomic( true );
  11236. }
  11237. /**
  11238. * Returns attribute data for this storage buffer node.
  11239. *
  11240. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11241. */
  11242. getAttributeData() {
  11243. if ( this._attribute === null ) {
  11244. this._attribute = bufferAttribute( this.value );
  11245. this._varying = varying( this._attribute );
  11246. }
  11247. return {
  11248. attribute: this._attribute,
  11249. varying: this._varying
  11250. };
  11251. }
  11252. /**
  11253. * This method is overwritten since the node type from the availability of storage buffers
  11254. * and the attribute data.
  11255. *
  11256. * @param {NodeBuilder} builder - The current node builder.
  11257. * @return {string} The node type.
  11258. */
  11259. getNodeType( builder ) {
  11260. if ( this.structTypeNode !== null ) {
  11261. return this.structTypeNode.getNodeType( builder );
  11262. }
  11263. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11264. return super.getNodeType( builder );
  11265. }
  11266. const { attribute } = this.getAttributeData();
  11267. return attribute.getNodeType( builder );
  11268. }
  11269. /**
  11270. * Returns the type of a member of the struct.
  11271. *
  11272. * @param {NodeBuilder} builder - The current node builder.
  11273. * @param {string} name - The name of the member.
  11274. * @return {string} The type of the member.
  11275. */
  11276. getMemberType( builder, name ) {
  11277. if ( this.structTypeNode !== null ) {
  11278. return this.structTypeNode.getMemberType( builder, name );
  11279. }
  11280. return 'void';
  11281. }
  11282. /**
  11283. * Generates the code snippet of the storage buffer node.
  11284. *
  11285. * @param {NodeBuilder} builder - The current node builder.
  11286. * @return {string} The generated code snippet.
  11287. */
  11288. generate( builder ) {
  11289. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  11290. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11291. return super.generate( builder );
  11292. }
  11293. const { attribute, varying } = this.getAttributeData();
  11294. const output = varying.build( builder );
  11295. builder.registerTransform( output, attribute );
  11296. return output;
  11297. }
  11298. }
  11299. /**
  11300. * TSL function for creating a storage buffer node.
  11301. *
  11302. * @tsl
  11303. * @function
  11304. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11305. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  11306. * @param {number} [count=0] - The buffer count.
  11307. * @returns {StorageBufferNode}
  11308. */
  11309. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11310. /**
  11311. * @tsl
  11312. * @function
  11313. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  11314. *
  11315. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11316. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  11317. * @param {number} count - The buffer count.
  11318. * @returns {StorageBufferNode}
  11319. */
  11320. const storageObject = ( value, type, count ) => { // @deprecated, r171
  11321. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  11322. return storage( value, type, count ).setPBO( true );
  11323. };
  11324. const _frameId = new WeakMap();
  11325. /**
  11326. * This node implements the vertex transformation shader logic which is required
  11327. * for skinning/skeletal animation.
  11328. *
  11329. * @augments Node
  11330. */
  11331. class SkinningNode extends Node {
  11332. static get type() {
  11333. return 'SkinningNode';
  11334. }
  11335. /**
  11336. * Constructs a new skinning node.
  11337. *
  11338. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11339. */
  11340. constructor( skinnedMesh ) {
  11341. super( 'void' );
  11342. /**
  11343. * The skinned mesh.
  11344. *
  11345. * @type {SkinnedMesh}
  11346. */
  11347. this.skinnedMesh = skinnedMesh;
  11348. /**
  11349. * The update type overwritten since skinning nodes are updated per object.
  11350. *
  11351. * @type {string}
  11352. */
  11353. this.updateType = NodeUpdateType.OBJECT;
  11354. //
  11355. /**
  11356. * The skin index attribute.
  11357. *
  11358. * @type {AttributeNode}
  11359. */
  11360. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  11361. /**
  11362. * The skin weight attribute.
  11363. *
  11364. * @type {AttributeNode}
  11365. */
  11366. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  11367. /**
  11368. * The bind matrix node.
  11369. *
  11370. * @type {Node<mat4>}
  11371. */
  11372. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  11373. /**
  11374. * The bind matrix inverse node.
  11375. *
  11376. * @type {Node<mat4>}
  11377. */
  11378. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  11379. /**
  11380. * The bind matrices as a uniform buffer node.
  11381. *
  11382. * @type {Node}
  11383. */
  11384. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11385. /**
  11386. * The current vertex position in local space.
  11387. *
  11388. * @type {Node<vec3>}
  11389. */
  11390. this.positionNode = positionLocal;
  11391. /**
  11392. * The result of vertex position in local space.
  11393. *
  11394. * @type {Node<vec3>}
  11395. */
  11396. this.toPositionNode = positionLocal;
  11397. /**
  11398. * The previous bind matrices as a uniform buffer node.
  11399. * Required for computing motion vectors.
  11400. *
  11401. * @type {?Node}
  11402. * @default null
  11403. */
  11404. this.previousBoneMatricesNode = null;
  11405. }
  11406. /**
  11407. * Transforms the given vertex position via skinning.
  11408. *
  11409. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11410. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  11411. * @return {Node<vec3>} The transformed vertex position.
  11412. */
  11413. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  11414. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11415. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11416. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11417. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11418. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11419. // POSITION
  11420. const skinVertex = bindMatrixNode.mul( position );
  11421. const skinned = add(
  11422. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  11423. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  11424. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  11425. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  11426. );
  11427. return bindMatrixInverseNode.mul( skinned ).xyz;
  11428. }
  11429. /**
  11430. * Transforms the given vertex normal via skinning.
  11431. *
  11432. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11433. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  11434. * @return {Node<vec3>} The transformed vertex normal.
  11435. */
  11436. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  11437. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11438. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11439. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11440. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11441. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11442. // NORMAL
  11443. let skinMatrix = add(
  11444. skinWeightNode.x.mul( boneMatX ),
  11445. skinWeightNode.y.mul( boneMatY ),
  11446. skinWeightNode.z.mul( boneMatZ ),
  11447. skinWeightNode.w.mul( boneMatW )
  11448. );
  11449. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  11450. return skinMatrix.transformDirection( normal ).xyz;
  11451. }
  11452. /**
  11453. * Computes the transformed/skinned vertex position of the previous frame.
  11454. *
  11455. * @param {NodeBuilder} builder - The current node builder.
  11456. * @return {Node<vec3>} The skinned position from the previous frame.
  11457. */
  11458. getPreviousSkinnedPosition( builder ) {
  11459. const skinnedMesh = builder.object;
  11460. if ( this.previousBoneMatricesNode === null ) {
  11461. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  11462. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11463. }
  11464. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  11465. }
  11466. /**
  11467. * Returns `true` if bone matrices from the previous frame are required. Relevant
  11468. * when computing motion vectors with {@link VelocityNode}.
  11469. *
  11470. * @param {NodeBuilder} builder - The current node builder.
  11471. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  11472. */
  11473. needsPreviousBoneMatrices( builder ) {
  11474. const mrt = builder.renderer.getMRT();
  11475. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  11476. }
  11477. /**
  11478. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  11479. *
  11480. * @param {NodeBuilder} builder - The current node builder.
  11481. * @return {Node<vec3>} The transformed vertex position.
  11482. */
  11483. setup( builder ) {
  11484. if ( this.needsPreviousBoneMatrices( builder ) ) {
  11485. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  11486. }
  11487. const skinPosition = this.getSkinnedPosition();
  11488. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  11489. //
  11490. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11491. const skinNormal = this.getSkinnedNormal();
  11492. normalLocal.assign( skinNormal );
  11493. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11494. tangentLocal.assign( skinNormal );
  11495. }
  11496. }
  11497. return skinPosition;
  11498. }
  11499. /**
  11500. * Generates the code snippet of the skinning node.
  11501. *
  11502. * @param {NodeBuilder} builder - The current node builder.
  11503. * @param {string} output - The current output.
  11504. * @return {string} The generated code snippet.
  11505. */
  11506. generate( builder, output ) {
  11507. if ( output !== 'void' ) {
  11508. return super.generate( builder, output );
  11509. }
  11510. }
  11511. /**
  11512. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  11513. *
  11514. * @param {NodeFrame} frame - The current node frame.
  11515. */
  11516. update( frame ) {
  11517. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  11518. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  11519. _frameId.set( skeleton, frame.frameId );
  11520. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  11521. skeleton.update();
  11522. }
  11523. }
  11524. /**
  11525. * TSL function for creating a skinning node.
  11526. *
  11527. * @tsl
  11528. * @function
  11529. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11530. * @returns {SkinningNode}
  11531. */
  11532. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  11533. /**
  11534. * TSL function for computing skinning.
  11535. *
  11536. * @tsl
  11537. * @function
  11538. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11539. * @param {Node<vec3>} [toPosition=null] - The target position.
  11540. * @returns {SkinningNode}
  11541. */
  11542. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  11543. const node = new SkinningNode( skinnedMesh );
  11544. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11545. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11546. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11547. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  11548. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  11549. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  11550. node.toPositionNode = toPosition;
  11551. return nodeObject( node );
  11552. };
  11553. /**
  11554. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  11555. * ```js
  11556. * Loop( count, ( { i } ) => {
  11557. *
  11558. * } );
  11559. * ```
  11560. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  11561. * ```js
  11562. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  11563. *
  11564. * } );
  11565. *```
  11566. * Nested loops can be defined in a compacted form:
  11567. * ```js
  11568. * Loop( 10, 5, ( { i, j } ) => {
  11569. *
  11570. * } );
  11571. * ```
  11572. * Loops that should run backwards can be defined like so:
  11573. * ```js
  11574. * Loop( { start: 10 }, () => {} );
  11575. * ```
  11576. * It is possible to execute with boolean values, similar to the `while` syntax.
  11577. * ```js
  11578. * const value = float( 0 ).toVar();
  11579. *
  11580. * Loop( value.lessThan( 10 ), () => {
  11581. *
  11582. * value.addAssign( 1 );
  11583. *
  11584. * } );
  11585. * ```
  11586. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  11587. * @augments Node
  11588. */
  11589. class LoopNode extends Node {
  11590. static get type() {
  11591. return 'LoopNode';
  11592. }
  11593. /**
  11594. * Constructs a new loop node.
  11595. *
  11596. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  11597. */
  11598. constructor( params = [] ) {
  11599. super();
  11600. this.params = params;
  11601. }
  11602. /**
  11603. * Returns a loop variable name based on an index. The pattern is
  11604. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  11605. *
  11606. * @param {number} index - The index.
  11607. * @return {string} The loop variable name.
  11608. */
  11609. getVarName( index ) {
  11610. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  11611. }
  11612. /**
  11613. * Returns properties about this node.
  11614. *
  11615. * @param {NodeBuilder} builder - The current node builder.
  11616. * @return {Object} The node properties.
  11617. */
  11618. getProperties( builder ) {
  11619. const properties = builder.getNodeProperties( this );
  11620. if ( properties.stackNode !== undefined ) return properties;
  11621. //
  11622. const inputs = {};
  11623. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11624. const param = this.params[ i ];
  11625. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  11626. const type = ( param.isNode !== true && param.type ) || 'int';
  11627. inputs[ name ] = expression( name, type );
  11628. }
  11629. const stack = builder.addStack(); // TODO: cache() it
  11630. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  11631. properties.stackNode = stack;
  11632. const baseParam = this.params[ 0 ];
  11633. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  11634. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  11635. }
  11636. builder.removeStack();
  11637. return properties;
  11638. }
  11639. /**
  11640. * This method is overwritten since the node type is inferred based on the loop configuration.
  11641. *
  11642. * @param {NodeBuilder} builder - The current node builder.
  11643. * @return {string} The node type.
  11644. */
  11645. getNodeType( builder ) {
  11646. const { returnsNode } = this.getProperties( builder );
  11647. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  11648. }
  11649. setup( builder ) {
  11650. // setup properties
  11651. this.getProperties( builder );
  11652. }
  11653. generate( builder ) {
  11654. const properties = this.getProperties( builder );
  11655. const params = this.params;
  11656. const stackNode = properties.stackNode;
  11657. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  11658. const param = params[ i ];
  11659. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  11660. if ( param.isNode ) {
  11661. if ( param.getNodeType( builder ) === 'bool' ) {
  11662. isWhile = true;
  11663. type = 'bool';
  11664. end = param.build( builder, type );
  11665. } else {
  11666. type = 'int';
  11667. name = this.getVarName( i );
  11668. start = '0';
  11669. end = param.build( builder, type );
  11670. condition = '<';
  11671. }
  11672. } else {
  11673. type = param.type || 'int';
  11674. name = param.name || this.getVarName( i );
  11675. start = param.start;
  11676. end = param.end;
  11677. condition = param.condition;
  11678. update = param.update;
  11679. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  11680. else if ( start && start.isNode ) start = start.build( builder, type );
  11681. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  11682. else if ( end && end.isNode ) end = end.build( builder, type );
  11683. if ( start !== undefined && end === undefined ) {
  11684. start = start + ' - 1';
  11685. end = '0';
  11686. condition = '>=';
  11687. } else if ( end !== undefined && start === undefined ) {
  11688. start = '0';
  11689. condition = '<';
  11690. }
  11691. if ( condition === undefined ) {
  11692. if ( Number( start ) > Number( end ) ) {
  11693. condition = '>=';
  11694. } else {
  11695. condition = '<';
  11696. }
  11697. }
  11698. }
  11699. let loopSnippet;
  11700. if ( isWhile ) {
  11701. loopSnippet = `while ( ${ end } )`;
  11702. } else {
  11703. const internalParam = { start, end};
  11704. //
  11705. const startSnippet = internalParam.start;
  11706. const endSnippet = internalParam.end;
  11707. let updateSnippet;
  11708. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  11709. if ( update !== undefined && update !== null ) {
  11710. switch ( typeof update ) {
  11711. case 'function':
  11712. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  11713. const snippet = flow.code.replace( /\t|;/g, '' );
  11714. updateSnippet = snippet;
  11715. break;
  11716. case 'number':
  11717. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  11718. break;
  11719. case 'string':
  11720. updateSnippet = name + ' ' + update;
  11721. break;
  11722. default:
  11723. if ( update.isNode ) {
  11724. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  11725. } else {
  11726. console.error( 'THREE.TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  11727. updateSnippet = 'break /* invalid update */';
  11728. }
  11729. }
  11730. } else {
  11731. if ( type === 'int' || type === 'uint' ) {
  11732. update = condition.includes( '<' ) ? '++' : '--';
  11733. } else {
  11734. update = deltaOperator() + ' 1.';
  11735. }
  11736. updateSnippet = name + ' ' + update;
  11737. }
  11738. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  11739. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  11740. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  11741. }
  11742. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  11743. }
  11744. const stackSnippet = stackNode.build( builder, 'void' );
  11745. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  11746. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  11747. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11748. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  11749. }
  11750. builder.addFlowTab();
  11751. return returnsSnippet;
  11752. }
  11753. }
  11754. /**
  11755. * TSL function for creating a loop node.
  11756. *
  11757. * @tsl
  11758. * @function
  11759. * @param {...any} params - A list of parameters.
  11760. * @returns {LoopNode}
  11761. */
  11762. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  11763. /**
  11764. * TSL function for creating a `Continue()` expression.
  11765. *
  11766. * @tsl
  11767. * @function
  11768. * @returns {ExpressionNode}
  11769. */
  11770. const Continue = () => expression( 'continue' ).toStack();
  11771. /**
  11772. * TSL function for creating a `Break()` expression.
  11773. *
  11774. * @tsl
  11775. * @function
  11776. * @returns {ExpressionNode}
  11777. */
  11778. const Break = () => expression( 'break' ).toStack();
  11779. const _morphTextures = /*@__PURE__*/ new WeakMap();
  11780. const _morphVec4 = /*@__PURE__*/ new Vector4();
  11781. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  11782. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  11783. const y = texelIndex.div( width );
  11784. const x = texelIndex.sub( y.mul( width ) );
  11785. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  11786. return bufferAttrib.mul( influence );
  11787. } );
  11788. function getEntry( geometry ) {
  11789. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11790. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  11791. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  11792. // instead of using attributes, the WebGL 2 code path encodes morph targets
  11793. // into an array of data textures. Each layer represents a single morph target.
  11794. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11795. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11796. let entry = _morphTextures.get( geometry );
  11797. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  11798. if ( entry !== undefined ) entry.texture.dispose();
  11799. const morphTargets = geometry.morphAttributes.position || [];
  11800. const morphNormals = geometry.morphAttributes.normal || [];
  11801. const morphColors = geometry.morphAttributes.color || [];
  11802. let vertexDataCount = 0;
  11803. if ( hasMorphPosition === true ) vertexDataCount = 1;
  11804. if ( hasMorphNormals === true ) vertexDataCount = 2;
  11805. if ( hasMorphColors === true ) vertexDataCount = 3;
  11806. let width = geometry.attributes.position.count * vertexDataCount;
  11807. let height = 1;
  11808. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  11809. if ( width > maxTextureSize ) {
  11810. height = Math.ceil( width / maxTextureSize );
  11811. width = maxTextureSize;
  11812. }
  11813. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  11814. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  11815. bufferTexture.type = FloatType;
  11816. bufferTexture.needsUpdate = true;
  11817. // fill buffer
  11818. const vertexDataStride = vertexDataCount * 4;
  11819. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  11820. const morphTarget = morphTargets[ i ];
  11821. const morphNormal = morphNormals[ i ];
  11822. const morphColor = morphColors[ i ];
  11823. const offset = width * height * 4 * i;
  11824. for ( let j = 0; j < morphTarget.count; j ++ ) {
  11825. const stride = j * vertexDataStride;
  11826. if ( hasMorphPosition === true ) {
  11827. _morphVec4.fromBufferAttribute( morphTarget, j );
  11828. buffer[ offset + stride + 0 ] = _morphVec4.x;
  11829. buffer[ offset + stride + 1 ] = _morphVec4.y;
  11830. buffer[ offset + stride + 2 ] = _morphVec4.z;
  11831. buffer[ offset + stride + 3 ] = 0;
  11832. }
  11833. if ( hasMorphNormals === true ) {
  11834. _morphVec4.fromBufferAttribute( morphNormal, j );
  11835. buffer[ offset + stride + 4 ] = _morphVec4.x;
  11836. buffer[ offset + stride + 5 ] = _morphVec4.y;
  11837. buffer[ offset + stride + 6 ] = _morphVec4.z;
  11838. buffer[ offset + stride + 7 ] = 0;
  11839. }
  11840. if ( hasMorphColors === true ) {
  11841. _morphVec4.fromBufferAttribute( morphColor, j );
  11842. buffer[ offset + stride + 8 ] = _morphVec4.x;
  11843. buffer[ offset + stride + 9 ] = _morphVec4.y;
  11844. buffer[ offset + stride + 10 ] = _morphVec4.z;
  11845. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  11846. }
  11847. }
  11848. }
  11849. entry = {
  11850. count: morphTargetsCount,
  11851. texture: bufferTexture,
  11852. stride: vertexDataCount,
  11853. size: new Vector2( width, height )
  11854. };
  11855. _morphTextures.set( geometry, entry );
  11856. function disposeTexture() {
  11857. bufferTexture.dispose();
  11858. _morphTextures.delete( geometry );
  11859. geometry.removeEventListener( 'dispose', disposeTexture );
  11860. }
  11861. geometry.addEventListener( 'dispose', disposeTexture );
  11862. }
  11863. return entry;
  11864. }
  11865. /**
  11866. * This node implements the vertex transformation shader logic which is required
  11867. * for morph target animation.
  11868. *
  11869. * @augments Node
  11870. */
  11871. class MorphNode extends Node {
  11872. static get type() {
  11873. return 'MorphNode';
  11874. }
  11875. /**
  11876. * Constructs a new morph node.
  11877. *
  11878. * @param {Mesh} mesh - The mesh holding the morph targets.
  11879. */
  11880. constructor( mesh ) {
  11881. super( 'void' );
  11882. /**
  11883. * The mesh holding the morph targets.
  11884. *
  11885. * @type {Mesh}
  11886. */
  11887. this.mesh = mesh;
  11888. /**
  11889. * A uniform node which represents the morph base influence value.
  11890. *
  11891. * @type {UniformNode<float>}
  11892. */
  11893. this.morphBaseInfluence = uniform( 1 );
  11894. /**
  11895. * The update type overwritten since morph nodes are updated per object.
  11896. *
  11897. * @type {string}
  11898. */
  11899. this.updateType = NodeUpdateType.OBJECT;
  11900. }
  11901. /**
  11902. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  11903. *
  11904. * @param {NodeBuilder} builder - The current node builder.
  11905. */
  11906. setup( builder ) {
  11907. const { geometry } = builder;
  11908. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11909. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  11910. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11911. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11912. // nodes
  11913. const { texture: bufferMap, stride, size } = getEntry( geometry );
  11914. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  11915. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  11916. const width = int( size.width );
  11917. Loop( morphTargetsCount, ( { i } ) => {
  11918. const influence = float( 0 ).toVar();
  11919. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  11920. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  11921. } else {
  11922. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  11923. }
  11924. If( influence.notEqual( 0 ), () => {
  11925. if ( hasMorphPosition === true ) {
  11926. positionLocal.addAssign( getMorph( {
  11927. bufferMap,
  11928. influence,
  11929. stride,
  11930. width,
  11931. depth: i,
  11932. offset: int( 0 )
  11933. } ) );
  11934. }
  11935. if ( hasMorphNormals === true ) {
  11936. normalLocal.addAssign( getMorph( {
  11937. bufferMap,
  11938. influence,
  11939. stride,
  11940. width,
  11941. depth: i,
  11942. offset: int( 1 )
  11943. } ) );
  11944. }
  11945. } );
  11946. } );
  11947. }
  11948. /**
  11949. * Updates the state of the morphed mesh by updating the base influence.
  11950. *
  11951. * @param {NodeFrame} frame - The current node frame.
  11952. */
  11953. update( /*frame*/ ) {
  11954. const morphBaseInfluence = this.morphBaseInfluence;
  11955. if ( this.mesh.geometry.morphTargetsRelative ) {
  11956. morphBaseInfluence.value = 1;
  11957. } else {
  11958. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  11959. }
  11960. }
  11961. }
  11962. /**
  11963. * TSL function for creating a morph node.
  11964. *
  11965. * @tsl
  11966. * @function
  11967. * @param {Mesh} mesh - The mesh holding the morph targets.
  11968. * @returns {MorphNode}
  11969. */
  11970. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  11971. /**
  11972. * Base class for lighting nodes.
  11973. *
  11974. * @augments Node
  11975. */
  11976. class LightingNode extends Node {
  11977. static get type() {
  11978. return 'LightingNode';
  11979. }
  11980. /**
  11981. * Constructs a new lighting node.
  11982. */
  11983. constructor() {
  11984. super( 'vec3' );
  11985. /**
  11986. * This flag can be used for type testing.
  11987. *
  11988. * @type {boolean}
  11989. * @readonly
  11990. * @default true
  11991. */
  11992. this.isLightingNode = true;
  11993. }
  11994. }
  11995. /**
  11996. * A generic class that can be used by nodes which contribute
  11997. * ambient occlusion to the scene. E.g. an ambient occlusion map
  11998. * node can be used as input for this module. Used in {@link NodeMaterial}.
  11999. *
  12000. * @augments LightingNode
  12001. */
  12002. class AONode extends LightingNode {
  12003. static get type() {
  12004. return 'AONode';
  12005. }
  12006. /**
  12007. * Constructs a new AO node.
  12008. *
  12009. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12010. */
  12011. constructor( aoNode = null ) {
  12012. super();
  12013. /**
  12014. * The ambient occlusion node.
  12015. *
  12016. * @type {?Node<float>}
  12017. * @default null
  12018. */
  12019. this.aoNode = aoNode;
  12020. }
  12021. setup( builder ) {
  12022. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  12023. }
  12024. }
  12025. /**
  12026. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  12027. * by adding lighting specific context data. It represents the runtime context of
  12028. * {@link LightsNode}.
  12029. *
  12030. * @augments ContextNode
  12031. */
  12032. class LightingContextNode extends ContextNode {
  12033. static get type() {
  12034. return 'LightingContextNode';
  12035. }
  12036. /**
  12037. * Constructs a new lighting context node.
  12038. *
  12039. * @param {LightsNode} lightsNode - The lights node.
  12040. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  12041. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  12042. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  12043. */
  12044. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  12045. super( lightsNode );
  12046. /**
  12047. * The current lighting model.
  12048. *
  12049. * @type {?LightingModel}
  12050. * @default null
  12051. */
  12052. this.lightingModel = lightingModel;
  12053. /**
  12054. * A backdrop node.
  12055. *
  12056. * @type {?Node<vec3>}
  12057. * @default null
  12058. */
  12059. this.backdropNode = backdropNode;
  12060. /**
  12061. * A backdrop alpha node.
  12062. *
  12063. * @type {?Node<float>}
  12064. * @default null
  12065. */
  12066. this.backdropAlphaNode = backdropAlphaNode;
  12067. this._value = null;
  12068. }
  12069. /**
  12070. * Returns a lighting context object.
  12071. *
  12072. * @return {{
  12073. * radiance: Node<vec3>,
  12074. * irradiance: Node<vec3>,
  12075. * iblIrradiance: Node<vec3>,
  12076. * ambientOcclusion: Node<float>,
  12077. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  12078. * backdrop: Node<vec3>,
  12079. * backdropAlpha: Node<float>
  12080. * }} The lighting context object.
  12081. */
  12082. getContext() {
  12083. const { backdropNode, backdropAlphaNode } = this;
  12084. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  12085. directSpecular = vec3().toVar( 'directSpecular' ),
  12086. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  12087. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  12088. const reflectedLight = {
  12089. directDiffuse,
  12090. directSpecular,
  12091. indirectDiffuse,
  12092. indirectSpecular
  12093. };
  12094. const context = {
  12095. radiance: vec3().toVar( 'radiance' ),
  12096. irradiance: vec3().toVar( 'irradiance' ),
  12097. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  12098. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  12099. reflectedLight,
  12100. backdrop: backdropNode,
  12101. backdropAlpha: backdropAlphaNode
  12102. };
  12103. return context;
  12104. }
  12105. setup( builder ) {
  12106. this.value = this._value || ( this._value = this.getContext() );
  12107. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  12108. return super.setup( builder );
  12109. }
  12110. }
  12111. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  12112. /**
  12113. * A generic class that can be used by nodes which contribute
  12114. * irradiance to the scene. E.g. a light map node can be used
  12115. * as input for this module. Used in {@link NodeMaterial}.
  12116. *
  12117. * @augments LightingNode
  12118. */
  12119. class IrradianceNode extends LightingNode {
  12120. static get type() {
  12121. return 'IrradianceNode';
  12122. }
  12123. /**
  12124. * Constructs a new irradiance node.
  12125. *
  12126. * @param {Node<vec3>} node - A node contributing irradiance.
  12127. */
  12128. constructor( node ) {
  12129. super();
  12130. /**
  12131. * A node contributing irradiance.
  12132. *
  12133. * @type {Node<vec3>}
  12134. */
  12135. this.node = node;
  12136. }
  12137. setup( builder ) {
  12138. builder.context.irradiance.addAssign( this.node );
  12139. }
  12140. }
  12141. let screenSizeVec, viewportVec;
  12142. /**
  12143. * This node provides a collection of screen related metrics.
  12144. * Depending on {@link ScreenNode#scope}, the nodes can represent
  12145. * resolution or viewport data as well as fragment or uv coordinates.
  12146. *
  12147. * @augments Node
  12148. */
  12149. class ScreenNode extends Node {
  12150. static get type() {
  12151. return 'ScreenNode';
  12152. }
  12153. /**
  12154. * Constructs a new screen node.
  12155. *
  12156. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  12157. */
  12158. constructor( scope ) {
  12159. super();
  12160. /**
  12161. * The node represents different metric depending on which scope is selected.
  12162. *
  12163. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  12164. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  12165. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  12166. * - `ScreenNode.UV`: Normalized coordinates.
  12167. *
  12168. * @type {('coordinate'|'viewport'|'size'|'uv')}
  12169. */
  12170. this.scope = scope;
  12171. /**
  12172. * This flag can be used for type testing.
  12173. *
  12174. * @type {boolean}
  12175. * @readonly
  12176. * @default true
  12177. */
  12178. this.isViewportNode = true;
  12179. }
  12180. /**
  12181. * This method is overwritten since the node type depends on the selected scope.
  12182. *
  12183. * @return {('vec2'|'vec4')} The node type.
  12184. */
  12185. getNodeType() {
  12186. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  12187. else return 'vec2';
  12188. }
  12189. /**
  12190. * This method is overwritten since the node's update type depends on the selected scope.
  12191. *
  12192. * @return {NodeUpdateType} The update type.
  12193. */
  12194. getUpdateType() {
  12195. let updateType = NodeUpdateType.NONE;
  12196. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  12197. updateType = NodeUpdateType.RENDER;
  12198. }
  12199. this.updateType = updateType;
  12200. return updateType;
  12201. }
  12202. /**
  12203. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  12204. * from the current renderer.
  12205. *
  12206. * @param {NodeFrame} frame - A reference to the current node frame.
  12207. */
  12208. update( { renderer } ) {
  12209. const renderTarget = renderer.getRenderTarget();
  12210. if ( this.scope === ScreenNode.VIEWPORT ) {
  12211. if ( renderTarget !== null ) {
  12212. viewportVec.copy( renderTarget.viewport );
  12213. } else {
  12214. renderer.getViewport( viewportVec );
  12215. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  12216. }
  12217. } else {
  12218. if ( renderTarget !== null ) {
  12219. screenSizeVec.width = renderTarget.width;
  12220. screenSizeVec.height = renderTarget.height;
  12221. } else {
  12222. renderer.getDrawingBufferSize( screenSizeVec );
  12223. }
  12224. }
  12225. }
  12226. setup( /*builder*/ ) {
  12227. const scope = this.scope;
  12228. let output = null;
  12229. if ( scope === ScreenNode.SIZE ) {
  12230. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  12231. } else if ( scope === ScreenNode.VIEWPORT ) {
  12232. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  12233. } else {
  12234. output = vec2( screenCoordinate.div( screenSize ) );
  12235. }
  12236. return output;
  12237. }
  12238. generate( builder ) {
  12239. if ( this.scope === ScreenNode.COORDINATE ) {
  12240. let coord = builder.getFragCoord();
  12241. if ( builder.isFlipY() ) {
  12242. // follow webgpu standards
  12243. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  12244. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  12245. }
  12246. return coord;
  12247. }
  12248. return super.generate( builder );
  12249. }
  12250. }
  12251. ScreenNode.COORDINATE = 'coordinate';
  12252. ScreenNode.VIEWPORT = 'viewport';
  12253. ScreenNode.SIZE = 'size';
  12254. ScreenNode.UV = 'uv';
  12255. // Screen
  12256. /**
  12257. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  12258. *
  12259. * @tsl
  12260. * @type {ScreenNode<vec2>}
  12261. */
  12262. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  12263. /**
  12264. * TSL object that represents the screen resolution in physical pixel units.
  12265. *
  12266. * @tsl
  12267. * @type {ScreenNode<vec2>}
  12268. */
  12269. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  12270. /**
  12271. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  12272. *
  12273. * @tsl
  12274. * @type {ScreenNode<vec2>}
  12275. */
  12276. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  12277. // Viewport
  12278. /**
  12279. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  12280. *
  12281. * @tsl
  12282. * @type {ScreenNode<vec4>}
  12283. */
  12284. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  12285. /**
  12286. * TSL object that represents the viewport resolution in physical pixel units.
  12287. *
  12288. * @tsl
  12289. * @type {ScreenNode<vec2>}
  12290. */
  12291. const viewportSize = viewport.zw;
  12292. /**
  12293. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  12294. *
  12295. * @tsl
  12296. * @type {ScreenNode<vec2>}
  12297. */
  12298. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  12299. /**
  12300. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  12301. *
  12302. * @tsl
  12303. * @type {ScreenNode<vec2>}
  12304. */
  12305. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  12306. // Deprecated
  12307. /**
  12308. * @deprecated since r169. Use {@link screenSize} instead.
  12309. */
  12310. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  12311. console.warn( 'THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  12312. return screenSize;
  12313. }, 'vec2' ).once() )();
  12314. const _size$4 = /*@__PURE__*/ new Vector2();
  12315. /**
  12316. * A special type of texture node which represents the data of the current viewport
  12317. * as a texture. The module extracts data from the current bound framebuffer with
  12318. * a copy operation so no extra render pass is required to produce the texture data
  12319. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  12320. * variety of effects like refractive or transmissive materials.
  12321. *
  12322. * @augments TextureNode
  12323. */
  12324. class ViewportTextureNode extends TextureNode {
  12325. static get type() {
  12326. return 'ViewportTextureNode';
  12327. }
  12328. /**
  12329. * Constructs a new viewport texture node.
  12330. *
  12331. * @param {Node} [uvNode=screenUV] - The uv node.
  12332. * @param {?Node} [levelNode=null] - The level node.
  12333. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12334. */
  12335. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  12336. let defaultFramebuffer = null;
  12337. if ( framebufferTexture === null ) {
  12338. defaultFramebuffer = new FramebufferTexture();
  12339. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  12340. framebufferTexture = defaultFramebuffer;
  12341. } else {
  12342. defaultFramebuffer = framebufferTexture;
  12343. }
  12344. super( framebufferTexture, uvNode, levelNode );
  12345. /**
  12346. * Whether to generate mipmaps or not.
  12347. *
  12348. * @type {boolean}
  12349. * @default false
  12350. */
  12351. this.generateMipmaps = false;
  12352. /**
  12353. * The reference framebuffer texture. This is used to store the framebuffer texture
  12354. * for the current render target. If the render target changes, a new framebuffer texture
  12355. * is created automatically.
  12356. *
  12357. * @type {FramebufferTexture}
  12358. * @default null
  12359. */
  12360. this.defaultFramebuffer = defaultFramebuffer;
  12361. /**
  12362. * This flag can be used for type testing.
  12363. *
  12364. * @type {boolean}
  12365. * @readonly
  12366. * @default true
  12367. */
  12368. this.isOutputTextureNode = true;
  12369. /**
  12370. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node renders the
  12371. * scene once per render in its {@link ViewportTextureNode#updateBefore} method.
  12372. *
  12373. * @type {string}
  12374. * @default 'frame'
  12375. */
  12376. this.updateBeforeType = NodeUpdateType.RENDER;
  12377. /**
  12378. * The framebuffer texture for the current renderer context.
  12379. *
  12380. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  12381. * @private
  12382. */
  12383. this._textures = new WeakMap();
  12384. }
  12385. getFrameBufferTexture( reference = null ) {
  12386. const defaultFramebuffer = this.referenceNode ? this.referenceNode.defaultFramebuffer : this.defaultFramebuffer;
  12387. if ( reference === null ) {
  12388. return defaultFramebuffer;
  12389. }
  12390. if ( this._textures.has( reference ) === false ) {
  12391. const framebufferTexture = defaultFramebuffer.clone();
  12392. this._textures.set( reference, framebufferTexture );
  12393. }
  12394. return this._textures.get( reference );
  12395. }
  12396. updateBefore( frame ) {
  12397. const renderer = frame.renderer;
  12398. const renderTarget = renderer.getRenderTarget();
  12399. if ( renderTarget === null ) {
  12400. renderer.getDrawingBufferSize( _size$4 );
  12401. } else {
  12402. _size$4.set( renderTarget.width, renderTarget.height );
  12403. }
  12404. //
  12405. const framebufferTexture = this.getFrameBufferTexture( renderTarget );
  12406. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  12407. framebufferTexture.image.width = _size$4.width;
  12408. framebufferTexture.image.height = _size$4.height;
  12409. framebufferTexture.needsUpdate = true;
  12410. }
  12411. //
  12412. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  12413. framebufferTexture.generateMipmaps = this.generateMipmaps;
  12414. renderer.copyFramebufferToTexture( framebufferTexture );
  12415. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  12416. this.value = framebufferTexture;
  12417. }
  12418. clone() {
  12419. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  12420. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  12421. return viewportTextureNode;
  12422. }
  12423. }
  12424. /**
  12425. * TSL function for creating a viewport texture node.
  12426. *
  12427. * @tsl
  12428. * @function
  12429. * @param {?Node} [uvNode=screenUV] - The uv node.
  12430. * @param {?Node} [levelNode=null] - The level node.
  12431. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12432. * @returns {ViewportTextureNode}
  12433. */
  12434. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  12435. /**
  12436. * TSL function for creating a viewport texture node with enabled mipmap generation.
  12437. *
  12438. * @tsl
  12439. * @function
  12440. * @param {?Node} [uvNode=screenUV] - The uv node.
  12441. * @param {?Node} [levelNode=null] - The level node.
  12442. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12443. * @returns {ViewportTextureNode}
  12444. */
  12445. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  12446. let sharedDepthbuffer = null;
  12447. /**
  12448. * Represents the depth of the current viewport as a texture. This module
  12449. * can be used in combination with viewport texture to achieve effects
  12450. * that require depth evaluation.
  12451. *
  12452. * @augments ViewportTextureNode
  12453. */
  12454. class ViewportDepthTextureNode extends ViewportTextureNode {
  12455. static get type() {
  12456. return 'ViewportDepthTextureNode';
  12457. }
  12458. /**
  12459. * Constructs a new viewport depth texture node.
  12460. *
  12461. * @param {Node} [uvNode=screenUV] - The uv node.
  12462. * @param {?Node} [levelNode=null] - The level node.
  12463. */
  12464. constructor( uvNode = screenUV, levelNode = null ) {
  12465. if ( sharedDepthbuffer === null ) {
  12466. sharedDepthbuffer = new DepthTexture();
  12467. }
  12468. super( uvNode, levelNode, sharedDepthbuffer );
  12469. }
  12470. }
  12471. /**
  12472. * TSL function for a viewport depth texture node.
  12473. *
  12474. * @tsl
  12475. * @function
  12476. * @param {?Node} [uvNode=screenUV] - The uv node.
  12477. * @param {?Node} [levelNode=null] - The level node.
  12478. * @returns {ViewportDepthTextureNode}
  12479. */
  12480. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  12481. /**
  12482. * This node offers a collection of features in context of the depth logic in the fragment shader.
  12483. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  12484. * fragment or for depth evaluation purposes.
  12485. *
  12486. * @augments Node
  12487. */
  12488. class ViewportDepthNode extends Node {
  12489. static get type() {
  12490. return 'ViewportDepthNode';
  12491. }
  12492. /**
  12493. * Constructs a new viewport depth node.
  12494. *
  12495. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  12496. * @param {?Node} [valueNode=null] - The value node.
  12497. */
  12498. constructor( scope, valueNode = null ) {
  12499. super( 'float' );
  12500. /**
  12501. * The node behaves differently depending on which scope is selected.
  12502. *
  12503. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  12504. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  12505. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  12506. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  12507. *
  12508. * @type {('depth'|'depthBase'|'linearDepth')}
  12509. */
  12510. this.scope = scope;
  12511. /**
  12512. * Can be used to define a custom depth value.
  12513. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  12514. *
  12515. * @type {?Node}
  12516. * @default null
  12517. */
  12518. this.valueNode = valueNode;
  12519. /**
  12520. * This flag can be used for type testing.
  12521. *
  12522. * @type {boolean}
  12523. * @readonly
  12524. * @default true
  12525. */
  12526. this.isViewportDepthNode = true;
  12527. }
  12528. generate( builder ) {
  12529. const { scope } = this;
  12530. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12531. return builder.getFragDepth();
  12532. }
  12533. return super.generate( builder );
  12534. }
  12535. setup( { camera } ) {
  12536. const { scope } = this;
  12537. const value = this.valueNode;
  12538. let node = null;
  12539. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12540. if ( value !== null ) {
  12541. node = depthBase().assign( value );
  12542. }
  12543. } else if ( scope === ViewportDepthNode.DEPTH ) {
  12544. if ( camera.isPerspectiveCamera ) {
  12545. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  12546. } else {
  12547. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12548. }
  12549. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12550. if ( value !== null ) {
  12551. if ( camera.isPerspectiveCamera ) {
  12552. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12553. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12554. } else {
  12555. node = value;
  12556. }
  12557. } else {
  12558. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12559. }
  12560. }
  12561. return node;
  12562. }
  12563. }
  12564. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12565. ViewportDepthNode.DEPTH = 'depth';
  12566. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12567. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12568. /**
  12569. * TSL function for converting a viewZ value to an orthographic depth value.
  12570. *
  12571. * @tsl
  12572. * @function
  12573. * @param {Node<float>} viewZ - The viewZ node.
  12574. * @param {Node<float>} near - The camera's near value.
  12575. * @param {Node<float>} far - The camera's far value.
  12576. * @returns {Node<float>}
  12577. */
  12578. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12579. /**
  12580. * TSL function for converting an orthographic depth value to a viewZ value.
  12581. *
  12582. * @tsl
  12583. * @function
  12584. * @param {Node<float>} depth - The orthographic depth.
  12585. * @param {Node<float>} near - The camera's near value.
  12586. * @param {Node<float>} far - The camera's far value.
  12587. * @returns {Node<float>}
  12588. */
  12589. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12590. /**
  12591. * TSL function for converting a viewZ value to a perspective depth value.
  12592. *
  12593. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12594. *
  12595. * @tsl
  12596. * @function
  12597. * @param {Node<float>} viewZ - The viewZ node.
  12598. * @param {Node<float>} near - The camera's near value.
  12599. * @param {Node<float>} far - The camera's far value.
  12600. * @returns {Node<float>}
  12601. */
  12602. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12603. /**
  12604. * TSL function for converting a perspective depth value to a viewZ value.
  12605. *
  12606. * @tsl
  12607. * @function
  12608. * @param {Node<float>} depth - The perspective depth.
  12609. * @param {Node<float>} near - The camera's near value.
  12610. * @param {Node<float>} far - The camera's far value.
  12611. * @returns {Node<float>}
  12612. */
  12613. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  12614. /**
  12615. * TSL function for converting a viewZ value to a logarithmic depth value.
  12616. *
  12617. * @tsl
  12618. * @function
  12619. * @param {Node<float>} viewZ - The viewZ node.
  12620. * @param {Node<float>} near - The camera's near value.
  12621. * @param {Node<float>} far - The camera's far value.
  12622. * @returns {Node<float>}
  12623. */
  12624. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  12625. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  12626. // The final logarithmic depth formula used here is adapted from one described in an
  12627. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  12628. // which was an improvement upon an earlier formula one described in an
  12629. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  12630. // Ulrich's formula is the following:
  12631. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  12632. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  12633. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  12634. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  12635. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  12636. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  12637. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  12638. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  12639. // be used, and ultimately Ulrich's "near plane" version was chosen.
  12640. // Outerra eventually made another improvement to their original "C-constant" variant,
  12641. // but it still does not incorporate the camera near plane (for this version,
  12642. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  12643. // Here we make 4 changes to Ulrich's formula:
  12644. // 1. Clamp the camera near plane so we don't divide by 0.
  12645. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  12646. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  12647. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  12648. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  12649. // so we do the same here, hence the 'viewZ.negate()' call.
  12650. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  12651. near = near.max( 1e-6 ).toVar();
  12652. const numerator = log2( viewZ.negate().div( near ) );
  12653. const denominator = log2( far.div( near ) );
  12654. return numerator.div( denominator );
  12655. };
  12656. /**
  12657. * TSL function for converting a logarithmic depth value to a viewZ value.
  12658. *
  12659. * @tsl
  12660. * @function
  12661. * @param {Node<float>} depth - The logarithmic depth.
  12662. * @param {Node<float>} near - The camera's near value.
  12663. * @param {Node<float>} far - The camera's far value.
  12664. * @returns {Node<float>}
  12665. */
  12666. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  12667. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  12668. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  12669. // a negative viewZ).
  12670. const exponent = depth.mul( log( far.div( near ) ) );
  12671. return float( Math.E ).pow( exponent ).mul( near ).negate();
  12672. };
  12673. /**
  12674. * TSL function for defining a value for the current fragment's depth.
  12675. *
  12676. * @tsl
  12677. * @function
  12678. * @param {Node<float>} value - The depth value to set.
  12679. * @returns {ViewportDepthNode<float>}
  12680. */
  12681. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  12682. /**
  12683. * TSL object that represents the depth value for the current fragment.
  12684. *
  12685. * @tsl
  12686. * @type {ViewportDepthNode}
  12687. */
  12688. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  12689. /**
  12690. * TSL function for converting a perspective depth value to linear depth.
  12691. *
  12692. * @tsl
  12693. * @function
  12694. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  12695. * @returns {ViewportDepthNode<float>}
  12696. */
  12697. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  12698. /**
  12699. * TSL object that represents the linear (orthographic) depth value of the current fragment
  12700. *
  12701. * @tsl
  12702. * @type {ViewportDepthNode}
  12703. */
  12704. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  12705. depth.assign = ( value ) => depthBase( value );
  12706. /**
  12707. * This node is used in {@link NodeMaterial} to setup the clipping
  12708. * which can happen hardware-accelerated (if supported) and optionally
  12709. * use alpha-to-coverage for anti-aliasing clipped edges.
  12710. *
  12711. * @augments Node
  12712. */
  12713. class ClippingNode extends Node {
  12714. static get type() {
  12715. return 'ClippingNode';
  12716. }
  12717. /**
  12718. * Constructs a new clipping node.
  12719. *
  12720. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  12721. * the selected scope influences the behavior of the node and what type of code is generated.
  12722. */
  12723. constructor( scope = ClippingNode.DEFAULT ) {
  12724. super();
  12725. /**
  12726. * The node's scope. Similar to other nodes, the selected scope influences
  12727. * the behavior of the node and what type of code is generated.
  12728. *
  12729. * @type {('default'|'hardware'|'alphaToCoverage')}
  12730. */
  12731. this.scope = scope;
  12732. }
  12733. /**
  12734. * Setups the node depending on the selected scope.
  12735. *
  12736. * @param {NodeBuilder} builder - The current node builder.
  12737. * @return {Node} The result node.
  12738. */
  12739. setup( builder ) {
  12740. super.setup( builder );
  12741. const clippingContext = builder.clippingContext;
  12742. const { intersectionPlanes, unionPlanes } = clippingContext;
  12743. this.hardwareClipping = builder.material.hardwareClipping;
  12744. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  12745. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  12746. } else if ( this.scope === ClippingNode.HARDWARE ) {
  12747. return this.setupHardwareClipping( unionPlanes, builder );
  12748. } else {
  12749. return this.setupDefault( intersectionPlanes, unionPlanes );
  12750. }
  12751. }
  12752. /**
  12753. * Setups alpha to coverage.
  12754. *
  12755. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12756. * @param {Array<Vector4>} unionPlanes - The union planes.
  12757. * @return {Node} The result node.
  12758. */
  12759. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  12760. return Fn( () => {
  12761. const distanceToPlane = float().toVar( 'distanceToPlane' );
  12762. const distanceGradient = float().toVar( 'distanceToGradient' );
  12763. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  12764. const numUnionPlanes = unionPlanes.length;
  12765. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12766. const clippingPlanes = uniformArray( unionPlanes );
  12767. Loop( numUnionPlanes, ( { i } ) => {
  12768. const plane = clippingPlanes.element( i );
  12769. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12770. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12771. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  12772. } );
  12773. }
  12774. const numIntersectionPlanes = intersectionPlanes.length;
  12775. if ( numIntersectionPlanes > 0 ) {
  12776. const clippingPlanes = uniformArray( intersectionPlanes );
  12777. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  12778. Loop( numIntersectionPlanes, ( { i } ) => {
  12779. const plane = clippingPlanes.element( i );
  12780. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12781. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12782. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  12783. } );
  12784. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  12785. }
  12786. diffuseColor.a.mulAssign( clipOpacity );
  12787. diffuseColor.a.equal( 0.0 ).discard();
  12788. } )();
  12789. }
  12790. /**
  12791. * Setups the default clipping.
  12792. *
  12793. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12794. * @param {Array<Vector4>} unionPlanes - The union planes.
  12795. * @return {Node} The result node.
  12796. */
  12797. setupDefault( intersectionPlanes, unionPlanes ) {
  12798. return Fn( () => {
  12799. const numUnionPlanes = unionPlanes.length;
  12800. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12801. const clippingPlanes = uniformArray( unionPlanes );
  12802. Loop( numUnionPlanes, ( { i } ) => {
  12803. const plane = clippingPlanes.element( i );
  12804. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  12805. } );
  12806. }
  12807. const numIntersectionPlanes = intersectionPlanes.length;
  12808. if ( numIntersectionPlanes > 0 ) {
  12809. const clippingPlanes = uniformArray( intersectionPlanes );
  12810. const clipped = bool( true ).toVar( 'clipped' );
  12811. Loop( numIntersectionPlanes, ( { i } ) => {
  12812. const plane = clippingPlanes.element( i );
  12813. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  12814. } );
  12815. clipped.discard();
  12816. }
  12817. } )();
  12818. }
  12819. /**
  12820. * Setups hardware clipping.
  12821. *
  12822. * @param {Array<Vector4>} unionPlanes - The union planes.
  12823. * @param {NodeBuilder} builder - The current node builder.
  12824. * @return {Node} The result node.
  12825. */
  12826. setupHardwareClipping( unionPlanes, builder ) {
  12827. const numUnionPlanes = unionPlanes.length;
  12828. builder.enableHardwareClipping( numUnionPlanes );
  12829. return Fn( () => {
  12830. const clippingPlanes = uniformArray( unionPlanes );
  12831. const hw_clip_distances = builtin( builder.getClipDistance() );
  12832. Loop( numUnionPlanes, ( { i } ) => {
  12833. const plane = clippingPlanes.element( i );
  12834. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  12835. hw_clip_distances.element( i ).assign( distance );
  12836. } );
  12837. } )();
  12838. }
  12839. }
  12840. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  12841. ClippingNode.DEFAULT = 'default';
  12842. ClippingNode.HARDWARE = 'hardware';
  12843. /**
  12844. * TSL function for setting up the default clipping logic.
  12845. *
  12846. * @tsl
  12847. * @function
  12848. * @returns {ClippingNode}
  12849. */
  12850. const clipping = () => nodeObject( new ClippingNode() );
  12851. /**
  12852. * TSL function for setting up alpha to coverage.
  12853. *
  12854. * @tsl
  12855. * @function
  12856. * @returns {ClippingNode}
  12857. */
  12858. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  12859. /**
  12860. * TSL function for setting up hardware-based clipping.
  12861. *
  12862. * @tsl
  12863. * @function
  12864. * @returns {ClippingNode}
  12865. */
  12866. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  12867. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  12868. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  12869. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12870. 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 ) ) ) ) ) );
  12871. } );
  12872. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12873. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  12874. } );
  12875. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  12876. // Find the discretized derivatives of our coordinates
  12877. const maxDeriv = max$1(
  12878. length( dFdx( position.xyz ) ),
  12879. length( dFdy( position.xyz ) )
  12880. );
  12881. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  12882. // Find two nearest log-discretized noise scales
  12883. const pixScales = vec2(
  12884. exp2( floor( log2( pixScale ) ) ),
  12885. exp2( ceil( log2( pixScale ) ) )
  12886. );
  12887. // Compute alpha thresholds at our two noise scales
  12888. const alpha = vec2(
  12889. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  12890. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  12891. );
  12892. // Factor to interpolate lerp with
  12893. const lerpFactor = fract( log2( pixScale ) );
  12894. // Interpolate alpha threshold from noise at two scales
  12895. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  12896. // Pass into CDF to compute uniformly distrib threshold
  12897. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  12898. const cases = vec3(
  12899. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  12900. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  12901. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  12902. // Find our final, uniformly distributed alpha threshold (ατ)
  12903. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  12904. // Avoids ατ == 0. Could also do ατ =1-ατ
  12905. return clamp( threshold, 1.0e-6, 1.0 );
  12906. } ).setLayout( {
  12907. name: 'getAlphaHashThreshold',
  12908. type: 'float',
  12909. inputs: [
  12910. { name: 'position', type: 'vec3' }
  12911. ]
  12912. } );
  12913. /**
  12914. * An attribute node for representing vertex colors.
  12915. *
  12916. * @augments AttributeNode
  12917. */
  12918. class VertexColorNode extends AttributeNode {
  12919. static get type() {
  12920. return 'VertexColorNode';
  12921. }
  12922. /**
  12923. * Constructs a new vertex color node.
  12924. *
  12925. * @param {number} index - The attribute index.
  12926. */
  12927. constructor( index ) {
  12928. super( null, 'vec4' );
  12929. /**
  12930. * This flag can be used for type testing.
  12931. *
  12932. * @type {boolean}
  12933. * @readonly
  12934. * @default true
  12935. */
  12936. this.isVertexColorNode = true;
  12937. /**
  12938. * The attribute index to enable more than one sets of vertex colors.
  12939. *
  12940. * @type {number}
  12941. * @default 0
  12942. */
  12943. this.index = index;
  12944. }
  12945. /**
  12946. * Overwrites the default implementation by honoring the attribute index.
  12947. *
  12948. * @param {NodeBuilder} builder - The current node builder.
  12949. * @return {string} The attribute name.
  12950. */
  12951. getAttributeName( /*builder*/ ) {
  12952. const index = this.index;
  12953. return 'color' + ( index > 0 ? index : '' );
  12954. }
  12955. generate( builder ) {
  12956. const attributeName = this.getAttributeName( builder );
  12957. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  12958. let result;
  12959. if ( geometryAttribute === true ) {
  12960. result = super.generate( builder );
  12961. } else {
  12962. // Vertex color fallback should be white
  12963. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  12964. }
  12965. return result;
  12966. }
  12967. serialize( data ) {
  12968. super.serialize( data );
  12969. data.index = this.index;
  12970. }
  12971. deserialize( data ) {
  12972. super.deserialize( data );
  12973. this.index = data.index;
  12974. }
  12975. }
  12976. /**
  12977. * TSL function for creating a reference node.
  12978. *
  12979. * @tsl
  12980. * @function
  12981. * @param {number} [index=0] - The attribute index.
  12982. * @returns {VertexColorNode}
  12983. */
  12984. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  12985. /**
  12986. * Represents a "Color Burn" blend mode.
  12987. *
  12988. * It's designed to darken the base layer's colors based on the color of the blend layer.
  12989. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  12990. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  12991. *
  12992. * @tsl
  12993. * @function
  12994. * @param {Node<vec3>} base - The base color.
  12995. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  12996. * @return {Node<vec3>} The result.
  12997. */
  12998. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  12999. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13000. } ).setLayout( {
  13001. name: 'blendBurn',
  13002. type: 'vec3',
  13003. inputs: [
  13004. { name: 'base', type: 'vec3' },
  13005. { name: 'blend', type: 'vec3' }
  13006. ]
  13007. } );
  13008. /**
  13009. * Represents a "Color Dodge" blend mode.
  13010. *
  13011. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13012. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13013. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13014. *
  13015. * @tsl
  13016. * @function
  13017. * @param {Node<vec3>} base - The base color.
  13018. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13019. * @return {Node<vec3>} The result.
  13020. */
  13021. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13022. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13023. } ).setLayout( {
  13024. name: 'blendDodge',
  13025. type: 'vec3',
  13026. inputs: [
  13027. { name: 'base', type: 'vec3' },
  13028. { name: 'blend', type: 'vec3' }
  13029. ]
  13030. } );
  13031. /**
  13032. * Represents a "Screen" blend mode.
  13033. *
  13034. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13035. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13036. * effects.
  13037. *
  13038. * @tsl
  13039. * @function
  13040. * @param {Node<vec3>} base - The base color.
  13041. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13042. * @return {Node<vec3>} The result.
  13043. */
  13044. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13045. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13046. } ).setLayout( {
  13047. name: 'blendScreen',
  13048. type: 'vec3',
  13049. inputs: [
  13050. { name: 'base', type: 'vec3' },
  13051. { name: 'blend', type: 'vec3' }
  13052. ]
  13053. } );
  13054. /**
  13055. * Represents a "Overlay" blend mode.
  13056. *
  13057. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13058. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13059. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13060. *
  13061. * @tsl
  13062. * @function
  13063. * @param {Node<vec3>} base - The base color.
  13064. * @param {Node<vec3>} blend - The blend color
  13065. * @return {Node<vec3>} The result.
  13066. */
  13067. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13068. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13069. } ).setLayout( {
  13070. name: 'blendOverlay',
  13071. type: 'vec3',
  13072. inputs: [
  13073. { name: 'base', type: 'vec3' },
  13074. { name: 'blend', type: 'vec3' }
  13075. ]
  13076. } );
  13077. /**
  13078. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13079. * It assumes both input colors have non-premultiplied alpha.
  13080. *
  13081. * @tsl
  13082. * @function
  13083. * @param {Node<vec4>} base - The base color.
  13084. * @param {Node<vec4>} blend - The blend color
  13085. * @return {Node<vec4>} The result.
  13086. */
  13087. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13088. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13089. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13090. } ).setLayout( {
  13091. name: 'blendColor',
  13092. type: 'vec4',
  13093. inputs: [
  13094. { name: 'base', type: 'vec4' },
  13095. { name: 'blend', type: 'vec4' }
  13096. ]
  13097. } );
  13098. /**
  13099. * Premultiplies the RGB channels of a color by its alpha channel.
  13100. *
  13101. * This function is useful for converting a non-premultiplied alpha color
  13102. * into a premultiplied alpha format, where the RGB values are scaled
  13103. * by the alpha value. Premultiplied alpha is often used in graphics
  13104. * rendering for certain operations, such as compositing and image processing.
  13105. *
  13106. * @tsl
  13107. * @function
  13108. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13109. * @return {Node<vec4>} The color with premultiplied alpha.
  13110. */
  13111. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13112. return vec4( color.rgb.mul( color.a ), color.a );
  13113. }, { color: 'vec4', return: 'vec4' } );
  13114. /**
  13115. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13116. *
  13117. * This function is useful for converting a premultiplied alpha color
  13118. * back into a non-premultiplied alpha format, where the RGB values are
  13119. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13120. * rendering for certain operations, such as compositing and image processing.
  13121. *
  13122. * @tsl
  13123. * @function
  13124. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13125. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13126. */
  13127. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13128. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13129. return vec4( color.rgb.div( color.a ), color.a );
  13130. }, { color: 'vec4', return: 'vec4' } );
  13131. // Deprecated
  13132. /**
  13133. * @tsl
  13134. * @function
  13135. * @deprecated since r171. Use {@link blendBurn} instead.
  13136. *
  13137. * @param {...any} params
  13138. * @returns {Function}
  13139. */
  13140. const burn = ( ...params ) => { // @deprecated, r171
  13141. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13142. return blendBurn( params );
  13143. };
  13144. /**
  13145. * @tsl
  13146. * @function
  13147. * @deprecated since r171. Use {@link blendDodge} instead.
  13148. *
  13149. * @param {...any} params
  13150. * @returns {Function}
  13151. */
  13152. const dodge = ( ...params ) => { // @deprecated, r171
  13153. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13154. return blendDodge( params );
  13155. };
  13156. /**
  13157. * @tsl
  13158. * @function
  13159. * @deprecated since r171. Use {@link blendScreen} instead.
  13160. *
  13161. * @param {...any} params
  13162. * @returns {Function}
  13163. */
  13164. const screen = ( ...params ) => { // @deprecated, r171
  13165. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13166. return blendScreen( params );
  13167. };
  13168. /**
  13169. * @tsl
  13170. * @function
  13171. * @deprecated since r171. Use {@link blendOverlay} instead.
  13172. *
  13173. * @param {...any} params
  13174. * @returns {Function}
  13175. */
  13176. const overlay = ( ...params ) => { // @deprecated, r171
  13177. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13178. return blendOverlay( params );
  13179. };
  13180. /**
  13181. * Base class for all node materials.
  13182. *
  13183. * @augments Material
  13184. */
  13185. class NodeMaterial extends Material {
  13186. static get type() {
  13187. return 'NodeMaterial';
  13188. }
  13189. /**
  13190. * Represents the type of the node material.
  13191. *
  13192. * @type {string}
  13193. */
  13194. get type() {
  13195. return this.constructor.type;
  13196. }
  13197. set type( _value ) { /* */ }
  13198. /**
  13199. * Constructs a new node material.
  13200. */
  13201. constructor() {
  13202. super();
  13203. /**
  13204. * This flag can be used for type testing.
  13205. *
  13206. * @type {boolean}
  13207. * @readonly
  13208. * @default true
  13209. */
  13210. this.isNodeMaterial = true;
  13211. /**
  13212. * Whether this material is affected by fog or not.
  13213. *
  13214. * @type {boolean}
  13215. * @default true
  13216. */
  13217. this.fog = true;
  13218. /**
  13219. * Whether this material is affected by lights or not.
  13220. *
  13221. * @type {boolean}
  13222. * @default false
  13223. */
  13224. this.lights = false;
  13225. /**
  13226. * Whether this material uses hardware clipping or not.
  13227. * This property is managed by the engine and should not be
  13228. * modified by apps.
  13229. *
  13230. * @type {boolean}
  13231. * @default false
  13232. */
  13233. this.hardwareClipping = false;
  13234. /**
  13235. * Node materials which set their `lights` property to `true`
  13236. * are affected by all lights of the scene. Sometimes selective
  13237. * lighting is wanted which means only _some_ lights in the scene
  13238. * affect a material. This can be achieved by creating an instance
  13239. * of {@link LightsNode} with a list of selective
  13240. * lights and assign the node to this property.
  13241. *
  13242. * ```js
  13243. * const customLightsNode = lights( [ light1, light2 ] );
  13244. * material.lightsNode = customLightsNode;
  13245. * ```
  13246. *
  13247. * @type {?LightsNode}
  13248. * @default null
  13249. */
  13250. this.lightsNode = null;
  13251. /**
  13252. * The environment of node materials can be defined by an environment
  13253. * map assigned to the `envMap` property or by `Scene.environment`
  13254. * if the node material is a PBR material. This node property allows to overwrite
  13255. * the default behavior and define the environment with a custom node.
  13256. *
  13257. * ```js
  13258. * material.envNode = pmremTexture( renderTarget.texture );
  13259. * ```
  13260. *
  13261. * @type {?Node<vec3>}
  13262. * @default null
  13263. */
  13264. this.envNode = null;
  13265. /**
  13266. * The lighting of node materials might be influenced by ambient occlusion.
  13267. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  13268. * and the respective `aoMapIntensity`. This node property allows to overwrite
  13269. * the default and define the ambient occlusion with a custom node instead.
  13270. *
  13271. * If you don't want to overwrite the diffuse color but modify the existing
  13272. * values instead, use {@link materialAO}.
  13273. *
  13274. * @type {?Node<float>}
  13275. * @default null
  13276. */
  13277. this.aoNode = null;
  13278. /**
  13279. * The diffuse color of node materials is by default inferred from the
  13280. * `color` and `map` properties. This node property allows to overwrite the default
  13281. * and define the diffuse color with a node instead.
  13282. *
  13283. * ```js
  13284. * material.colorNode = color( 0xff0000 ); // define red color
  13285. * ```
  13286. *
  13287. * If you don't want to overwrite the diffuse color but modify the existing
  13288. * values instead, use {@link materialColor}.
  13289. *
  13290. * ```js
  13291. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  13292. * ```
  13293. *
  13294. * @type {?Node<vec3>}
  13295. * @default null
  13296. */
  13297. this.colorNode = null;
  13298. /**
  13299. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  13300. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  13301. * and define the normals with a node instead.
  13302. *
  13303. * If you don't want to overwrite the normals but modify the existing values instead,
  13304. * use {@link materialNormal}.
  13305. *
  13306. * @type {?Node<vec3>}
  13307. * @default null
  13308. */
  13309. this.normalNode = null;
  13310. /**
  13311. * The opacity of node materials is by default inferred from the `opacity`
  13312. * and `alphaMap` properties. This node property allows to overwrite the default
  13313. * and define the opacity with a node instead.
  13314. *
  13315. * If you don't want to overwrite the normals but modify the existing
  13316. * value instead, use {@link materialOpacity}.
  13317. *
  13318. * @type {?Node<float>}
  13319. * @default null
  13320. */
  13321. this.opacityNode = null;
  13322. /**
  13323. * This node can be used to implement a variety of filter-like effects. The idea is
  13324. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  13325. * to create an arbitrary effect and then assign the node composition to this property.
  13326. * Everything behind the object using this material will now be affected by a filter.
  13327. *
  13328. * ```js
  13329. * const material = new NodeMaterial()
  13330. * material.transparent = true;
  13331. *
  13332. * // everything behind the object will be monochromatic
  13333. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  13334. * ```
  13335. *
  13336. * Backdrop computations are part of the lighting so only lit materials can use this property.
  13337. *
  13338. * @type {?Node<vec3>}
  13339. * @default null
  13340. */
  13341. this.backdropNode = null;
  13342. /**
  13343. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  13344. *
  13345. * @type {?Node<float>}
  13346. * @default null
  13347. */
  13348. this.backdropAlphaNode = null;
  13349. /**
  13350. * The alpha test of node materials is by default inferred from the `alphaTest`
  13351. * property. This node property allows to overwrite the default and define the
  13352. * alpha test with a node instead.
  13353. *
  13354. * If you don't want to overwrite the alpha test but modify the existing
  13355. * value instead, use {@link materialAlphaTest}.
  13356. *
  13357. * @type {?Node<float>}
  13358. * @default null
  13359. */
  13360. this.alphaTestNode = null;
  13361. /**
  13362. * Discards the fragment if the mask value is `false`.
  13363. *
  13364. * @type {?Node<bool>}
  13365. * @default null
  13366. */
  13367. this.maskNode = null;
  13368. /**
  13369. * The local vertex positions are computed based on multiple factors like the
  13370. * attribute data, morphing or skinning. This node property allows to overwrite
  13371. * the default and define local vertex positions with nodes instead.
  13372. *
  13373. * If you don't want to overwrite the vertex positions but modify the existing
  13374. * values instead, use {@link positionLocal}.
  13375. *
  13376. *```js
  13377. * material.positionNode = positionLocal.add( displace );
  13378. * ```
  13379. *
  13380. * @type {?Node<vec3>}
  13381. * @default null
  13382. */
  13383. this.positionNode = null;
  13384. /**
  13385. * This node property is intended for logic which modifies geometry data once or per animation step.
  13386. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  13387. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  13388. * can be implemented.
  13389. *
  13390. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  13391. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  13392. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  13393. * eventually assigned to `geometryNode`.
  13394. *
  13395. * @type {?Function}
  13396. * @default null
  13397. */
  13398. this.geometryNode = null;
  13399. /**
  13400. * Allows to overwrite depth values in the fragment shader.
  13401. *
  13402. * @type {?Node<float>}
  13403. * @default null
  13404. */
  13405. this.depthNode = null;
  13406. /**
  13407. * Allows to overwrite the position used for shadow map rendering which
  13408. * is by default {@link positionWorld}, the vertex position
  13409. * in world space.
  13410. *
  13411. * @type {?Node<float>}
  13412. * @default null
  13413. */
  13414. this.receivedShadowPositionNode = null;
  13415. /**
  13416. * Allows to overwrite the geometry position used for shadow map projection which
  13417. * is by default {@link positionLocal}, the vertex position in local space.
  13418. *
  13419. * @type {?Node<float>}
  13420. * @default null
  13421. */
  13422. this.castShadowPositionNode = null;
  13423. /**
  13424. * This node can be used to influence how an object using this node material
  13425. * receive shadows.
  13426. *
  13427. * ```js
  13428. * const totalShadows = float( 1 ).toVar();
  13429. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  13430. * totalShadows.mulAssign( shadow );
  13431. * //return float( 1 ); // bypass received shadows
  13432. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  13433. * } );
  13434. *
  13435. * @type {?(Function|FunctionNode<vec4>)}
  13436. * @default null
  13437. */
  13438. this.receivedShadowNode = null;
  13439. /**
  13440. * This node can be used to influence how an object using this node material
  13441. * casts shadows. To apply a color to shadows, you can simply do:
  13442. *
  13443. * ```js
  13444. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  13445. * ```
  13446. *
  13447. * Which can be nice to fake colored shadows of semi-transparent objects. It
  13448. * is also common to use the property with `Fn` function so checks are performed
  13449. * per fragment.
  13450. *
  13451. * ```js
  13452. * materialCustomShadow.castShadowNode = Fn( () => {
  13453. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  13454. * return materialColor;
  13455. * } )();
  13456. * ```
  13457. *
  13458. * @type {?Node<vec4>}
  13459. * @default null
  13460. */
  13461. this.castShadowNode = null;
  13462. /**
  13463. * This node can be used to define the final output of the material.
  13464. *
  13465. * TODO: Explain the differences to `fragmentNode`.
  13466. *
  13467. * @type {?Node<vec4>}
  13468. * @default null
  13469. */
  13470. this.outputNode = null;
  13471. /**
  13472. * MRT configuration is done on renderer or pass level. This node allows to
  13473. * overwrite what values are written into MRT targets on material level. This
  13474. * can be useful for implementing selective FX features that should only affect
  13475. * specific objects.
  13476. *
  13477. * @type {?MRTNode}
  13478. * @default null
  13479. */
  13480. this.mrtNode = null;
  13481. /**
  13482. * This node property can be used if you need complete freedom in implementing
  13483. * the fragment shader. Assigning a node will replace the built-in material
  13484. * logic used in the fragment stage.
  13485. *
  13486. * @type {?Node<vec4>}
  13487. * @default null
  13488. */
  13489. this.fragmentNode = null;
  13490. /**
  13491. * This node property can be used if you need complete freedom in implementing
  13492. * the vertex shader. Assigning a node will replace the built-in material logic
  13493. * used in the vertex stage.
  13494. *
  13495. * @type {?Node<vec4>}
  13496. * @default null
  13497. */
  13498. this.vertexNode = null;
  13499. // Deprecated properties
  13500. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  13501. get: () => {
  13502. return this.receivedShadowPositionNode;
  13503. },
  13504. set: ( value ) => {
  13505. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  13506. this.receivedShadowPositionNode = value;
  13507. }
  13508. } );
  13509. }
  13510. /**
  13511. * Allows to define a custom cache key that influence the material key computation
  13512. * for render objects.
  13513. *
  13514. * @return {string} The custom cache key.
  13515. */
  13516. customProgramCacheKey() {
  13517. return this.type + getCacheKey$1( this );
  13518. }
  13519. /**
  13520. * Builds this material with the given node builder.
  13521. *
  13522. * @param {NodeBuilder} builder - The current node builder.
  13523. */
  13524. build( builder ) {
  13525. this.setup( builder );
  13526. }
  13527. /**
  13528. * Setups a node material observer with the given builder.
  13529. *
  13530. * @param {NodeBuilder} builder - The current node builder.
  13531. * @return {NodeMaterialObserver} The node material observer.
  13532. */
  13533. setupObserver( builder ) {
  13534. return new NodeMaterialObserver( builder );
  13535. }
  13536. /**
  13537. * Setups the vertex and fragment stage of this node material.
  13538. *
  13539. * @param {NodeBuilder} builder - The current node builder.
  13540. */
  13541. setup( builder ) {
  13542. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  13543. builder.context.setupPositionView = () => this.setupPositionView( builder );
  13544. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  13545. const renderer = builder.renderer;
  13546. const renderTarget = renderer.getRenderTarget();
  13547. // < VERTEX STAGE >
  13548. builder.addStack();
  13549. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  13550. const vertexNode = this.vertexNode || mvp;
  13551. builder.stack.outputNode = vertexNode;
  13552. this.setupHardwareClipping( builder );
  13553. if ( this.geometryNode !== null ) {
  13554. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  13555. }
  13556. builder.addFlow( 'vertex', builder.removeStack() );
  13557. // < FRAGMENT STAGE >
  13558. builder.addStack();
  13559. let resultNode;
  13560. const clippingNode = this.setupClipping( builder );
  13561. if ( this.depthWrite === true || this.depthTest === true ) {
  13562. // only write depth if depth buffer is configured
  13563. if ( renderTarget !== null ) {
  13564. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  13565. } else {
  13566. if ( renderer.depth === true ) this.setupDepth( builder );
  13567. }
  13568. }
  13569. if ( this.fragmentNode === null ) {
  13570. this.setupDiffuseColor( builder );
  13571. this.setupVariants( builder );
  13572. const outgoingLightNode = this.setupLighting( builder );
  13573. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  13574. // force unsigned floats - useful for RenderTargets
  13575. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  13576. resultNode = this.setupOutput( builder, basicOutput );
  13577. // OUTPUT NODE
  13578. output.assign( resultNode );
  13579. //
  13580. const isCustomOutput = this.outputNode !== null;
  13581. if ( isCustomOutput ) resultNode = this.outputNode;
  13582. // MRT
  13583. if ( renderTarget !== null ) {
  13584. const mrt = renderer.getMRT();
  13585. const materialMRT = this.mrtNode;
  13586. if ( mrt !== null ) {
  13587. if ( isCustomOutput ) output.assign( resultNode );
  13588. resultNode = mrt;
  13589. if ( materialMRT !== null ) {
  13590. resultNode = mrt.merge( materialMRT );
  13591. }
  13592. } else if ( materialMRT !== null ) {
  13593. resultNode = materialMRT;
  13594. }
  13595. }
  13596. } else {
  13597. let fragmentNode = this.fragmentNode;
  13598. if ( fragmentNode.isOutputStructNode !== true ) {
  13599. fragmentNode = vec4( fragmentNode );
  13600. }
  13601. resultNode = this.setupOutput( builder, fragmentNode );
  13602. }
  13603. builder.stack.outputNode = resultNode;
  13604. builder.addFlow( 'fragment', builder.removeStack() );
  13605. // < OBSERVER >
  13606. builder.observer = this.setupObserver( builder );
  13607. }
  13608. /**
  13609. * Setups the clipping node.
  13610. *
  13611. * @param {NodeBuilder} builder - The current node builder.
  13612. * @return {ClippingNode} The clipping node.
  13613. */
  13614. setupClipping( builder ) {
  13615. if ( builder.clippingContext === null ) return null;
  13616. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  13617. let result = null;
  13618. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  13619. const samples = builder.renderer.samples;
  13620. if ( this.alphaToCoverage && samples > 1 ) {
  13621. // to be added to flow when the color/alpha value has been determined
  13622. result = clippingAlpha();
  13623. } else {
  13624. builder.stack.add( clipping() );
  13625. }
  13626. }
  13627. return result;
  13628. }
  13629. /**
  13630. * Setups the hardware clipping if available on the current device.
  13631. *
  13632. * @param {NodeBuilder} builder - The current node builder.
  13633. */
  13634. setupHardwareClipping( builder ) {
  13635. this.hardwareClipping = false;
  13636. if ( builder.clippingContext === null ) return;
  13637. const candidateCount = builder.clippingContext.unionPlanes.length;
  13638. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  13639. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  13640. builder.stack.add( hardwareClipping() );
  13641. this.hardwareClipping = true;
  13642. }
  13643. return;
  13644. }
  13645. /**
  13646. * Setups the depth of this material.
  13647. *
  13648. * @param {NodeBuilder} builder - The current node builder.
  13649. */
  13650. setupDepth( builder ) {
  13651. const { renderer, camera } = builder;
  13652. // Depth
  13653. let depthNode = this.depthNode;
  13654. if ( depthNode === null ) {
  13655. const mrt = renderer.getMRT();
  13656. if ( mrt && mrt.has( 'depth' ) ) {
  13657. depthNode = mrt.get( 'depth' );
  13658. } else if ( renderer.logarithmicDepthBuffer === true ) {
  13659. if ( camera.isPerspectiveCamera ) {
  13660. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  13661. } else {
  13662. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13663. }
  13664. }
  13665. }
  13666. if ( depthNode !== null ) {
  13667. depth.assign( depthNode ).toStack();
  13668. }
  13669. }
  13670. /**
  13671. * Setups the position node in view space. This method exists
  13672. * so derived node materials can modify the implementation e.g. sprite materials.
  13673. *
  13674. * @param {NodeBuilder} builder - The current node builder.
  13675. * @return {Node<vec3>} The position in view space.
  13676. */
  13677. setupPositionView( /*builder*/ ) {
  13678. return modelViewMatrix.mul( positionLocal ).xyz;
  13679. }
  13680. /**
  13681. * Setups the position in clip space.
  13682. *
  13683. * @param {NodeBuilder} builder - The current node builder.
  13684. * @return {Node<vec4>} The position in view space.
  13685. */
  13686. setupModelViewProjection( /*builder*/ ) {
  13687. return cameraProjectionMatrix.mul( positionView );
  13688. }
  13689. /**
  13690. * Setups the logic for the vertex stage.
  13691. *
  13692. * @param {NodeBuilder} builder - The current node builder.
  13693. * @return {Node<vec4>} The position in clip space.
  13694. */
  13695. setupVertex( builder ) {
  13696. builder.addStack();
  13697. this.setupPosition( builder );
  13698. builder.context.vertex = builder.removeStack();
  13699. return modelViewProjection;
  13700. }
  13701. /**
  13702. * Setups the computation of the position in local space.
  13703. *
  13704. * @param {NodeBuilder} builder - The current node builder.
  13705. * @return {Node<vec3>} The position in local space.
  13706. */
  13707. setupPosition( builder ) {
  13708. const { object, geometry } = builder;
  13709. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  13710. morphReference( object ).toStack();
  13711. }
  13712. if ( object.isSkinnedMesh === true ) {
  13713. skinning( object ).toStack();
  13714. }
  13715. if ( this.displacementMap ) {
  13716. const displacementMap = materialReference( 'displacementMap', 'texture' );
  13717. const displacementScale = materialReference( 'displacementScale', 'float' );
  13718. const displacementBias = materialReference( 'displacementBias', 'float' );
  13719. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  13720. }
  13721. if ( object.isBatchedMesh ) {
  13722. batch( object ).toStack();
  13723. }
  13724. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  13725. instancedMesh( object ).toStack();
  13726. }
  13727. if ( this.positionNode !== null ) {
  13728. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  13729. }
  13730. return positionLocal;
  13731. }
  13732. /**
  13733. * Setups the computation of the material's diffuse color.
  13734. *
  13735. * @param {NodeBuilder} builder - The current node builder.
  13736. * @param {BufferGeometry} geometry - The geometry.
  13737. */
  13738. setupDiffuseColor( { object, geometry } ) {
  13739. // MASK
  13740. if ( this.maskNode !== null ) {
  13741. // Discard if the mask is `false`
  13742. bool( this.maskNode ).not().discard();
  13743. }
  13744. // COLOR
  13745. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  13746. // VERTEX COLORS
  13747. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  13748. colorNode = colorNode.mul( vertexColor() );
  13749. }
  13750. // INSTANCED COLORS
  13751. if ( object.instanceColor ) {
  13752. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  13753. colorNode = instanceColor.mul( colorNode );
  13754. }
  13755. if ( object.isBatchedMesh && object._colorsTexture ) {
  13756. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  13757. colorNode = batchColor.mul( colorNode );
  13758. }
  13759. // DIFFUSE COLOR
  13760. diffuseColor.assign( colorNode );
  13761. // OPACITY
  13762. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13763. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  13764. // ALPHA TEST
  13765. let alphaTestNode = null;
  13766. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  13767. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  13768. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  13769. }
  13770. // ALPHA HASH
  13771. if ( this.alphaHash === true ) {
  13772. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  13773. }
  13774. // OPAQUE
  13775. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  13776. if ( isOpaque ) {
  13777. diffuseColor.a.assign( 1.0 );
  13778. } else if ( alphaTestNode === null ) {
  13779. diffuseColor.a.lessThanEqual( 0 ).discard();
  13780. }
  13781. }
  13782. /**
  13783. * Abstract interface method that can be implemented by derived materials
  13784. * to setup material-specific node variables.
  13785. *
  13786. * @abstract
  13787. * @param {NodeBuilder} builder - The current node builder.
  13788. */
  13789. setupVariants( /*builder*/ ) {
  13790. // Interface function.
  13791. }
  13792. /**
  13793. * Setups the outgoing light node variable
  13794. *
  13795. * @return {Node<vec3>} The outgoing light node.
  13796. */
  13797. setupOutgoingLight() {
  13798. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  13799. }
  13800. /**
  13801. * Setups the normal node from the material.
  13802. *
  13803. * @return {Node<vec3>} The normal node.
  13804. */
  13805. setupNormal() {
  13806. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  13807. }
  13808. /**
  13809. * Setups the environment node from the material.
  13810. *
  13811. * @param {NodeBuilder} builder - The current node builder.
  13812. * @return {Node<vec4>} The environment node.
  13813. */
  13814. setupEnvironment( /*builder*/ ) {
  13815. let node = null;
  13816. if ( this.envNode ) {
  13817. node = this.envNode;
  13818. } else if ( this.envMap ) {
  13819. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  13820. }
  13821. return node;
  13822. }
  13823. /**
  13824. * Setups the light map node from the material.
  13825. *
  13826. * @param {NodeBuilder} builder - The current node builder.
  13827. * @return {Node<vec3>} The light map node.
  13828. */
  13829. setupLightMap( builder ) {
  13830. let node = null;
  13831. if ( builder.material.lightMap ) {
  13832. node = new IrradianceNode( materialLightMap );
  13833. }
  13834. return node;
  13835. }
  13836. /**
  13837. * Setups the lights node based on the scene, environment and material.
  13838. *
  13839. * @param {NodeBuilder} builder - The current node builder.
  13840. * @return {LightsNode} The lights node.
  13841. */
  13842. setupLights( builder ) {
  13843. const materialLightsNode = [];
  13844. //
  13845. const envNode = this.setupEnvironment( builder );
  13846. if ( envNode && envNode.isLightingNode ) {
  13847. materialLightsNode.push( envNode );
  13848. }
  13849. const lightMapNode = this.setupLightMap( builder );
  13850. if ( lightMapNode && lightMapNode.isLightingNode ) {
  13851. materialLightsNode.push( lightMapNode );
  13852. }
  13853. if ( this.aoNode !== null || builder.material.aoMap ) {
  13854. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  13855. materialLightsNode.push( new AONode( aoNode ) );
  13856. }
  13857. let lightsN = this.lightsNode || builder.lightsNode;
  13858. if ( materialLightsNode.length > 0 ) {
  13859. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  13860. }
  13861. return lightsN;
  13862. }
  13863. /**
  13864. * This method should be implemented by most derived materials
  13865. * since it defines the material's lighting model.
  13866. *
  13867. * @abstract
  13868. * @param {NodeBuilder} builder - The current node builder.
  13869. * @return {LightingModel} The lighting model.
  13870. */
  13871. setupLightingModel( /*builder*/ ) {
  13872. // Interface function.
  13873. }
  13874. /**
  13875. * Setups the outgoing light node.
  13876. *
  13877. * @param {NodeBuilder} builder - The current node builder.
  13878. * @return {Node<vec3>} The outgoing light node.
  13879. */
  13880. setupLighting( builder ) {
  13881. const { material } = builder;
  13882. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  13883. // OUTGOING LIGHT
  13884. const lights = this.lights === true || this.lightsNode !== null;
  13885. const lightsNode = lights ? this.setupLights( builder ) : null;
  13886. let outgoingLightNode = this.setupOutgoingLight( builder );
  13887. if ( lightsNode && lightsNode.getScope().hasLights ) {
  13888. const lightingModel = this.setupLightingModel( builder ) || null;
  13889. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  13890. } else if ( backdropNode !== null ) {
  13891. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  13892. }
  13893. // EMISSIVE
  13894. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  13895. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  13896. outgoingLightNode = outgoingLightNode.add( emissive );
  13897. }
  13898. return outgoingLightNode;
  13899. }
  13900. /**
  13901. * Setup the fog.
  13902. *
  13903. * @param {NodeBuilder} builder - The current node builder.
  13904. * @param {Node<vec4>} outputNode - The existing output node.
  13905. * @return {Node<vec4>} The output node.
  13906. */
  13907. setupFog( builder, outputNode ) {
  13908. const fogNode = builder.fogNode;
  13909. if ( fogNode ) {
  13910. output.assign( outputNode );
  13911. outputNode = vec4( fogNode.toVar() );
  13912. }
  13913. return outputNode;
  13914. }
  13915. /**
  13916. * Setups premultiplied alpha.
  13917. *
  13918. * @param {NodeBuilder} builder - The current node builder.
  13919. * @param {Node<vec4>} outputNode - The existing output node.
  13920. * @return {Node<vec4>} The output node.
  13921. */
  13922. setupPremultipliedAlpha( builder, outputNode ) {
  13923. return premultiplyAlpha( outputNode );
  13924. }
  13925. /**
  13926. * Setups the output node.
  13927. *
  13928. * @param {NodeBuilder} builder - The current node builder.
  13929. * @param {Node<vec4>} outputNode - The existing output node.
  13930. * @return {Node<vec4>} The output node.
  13931. */
  13932. setupOutput( builder, outputNode ) {
  13933. // FOG
  13934. if ( this.fog === true ) {
  13935. outputNode = this.setupFog( builder, outputNode );
  13936. }
  13937. // PREMULTIPLIED ALPHA
  13938. if ( this.premultipliedAlpha === true ) {
  13939. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  13940. }
  13941. return outputNode;
  13942. }
  13943. /**
  13944. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  13945. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  13946. * defining all material properties of the classic type in the node type.
  13947. *
  13948. * @param {Material} material - The material to copy properties with their values to this node material.
  13949. */
  13950. setDefaultValues( material ) {
  13951. // This approach is to reuse the native refreshUniforms*
  13952. // and turn available the use of features like transmission and environment in core
  13953. for ( const property in material ) {
  13954. const value = material[ property ];
  13955. if ( this[ property ] === undefined ) {
  13956. this[ property ] = value;
  13957. if ( value && value.clone ) this[ property ] = value.clone();
  13958. }
  13959. }
  13960. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  13961. for ( const key in descriptors ) {
  13962. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  13963. descriptors[ key ].get !== undefined ) {
  13964. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  13965. }
  13966. }
  13967. }
  13968. /**
  13969. * Serializes this material to JSON.
  13970. *
  13971. * @param {?(Object|string)} meta - The meta information for serialization.
  13972. * @return {Object} The serialized node.
  13973. */
  13974. toJSON( meta ) {
  13975. const isRoot = ( meta === undefined || typeof meta === 'string' );
  13976. if ( isRoot ) {
  13977. meta = {
  13978. textures: {},
  13979. images: {},
  13980. nodes: {}
  13981. };
  13982. }
  13983. const data = Material.prototype.toJSON.call( this, meta );
  13984. const nodeChildren = getNodeChildren( this );
  13985. data.inputNodes = {};
  13986. for ( const { property, childNode } of nodeChildren ) {
  13987. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  13988. }
  13989. // TODO: Copied from Object3D.toJSON
  13990. function extractFromCache( cache ) {
  13991. const values = [];
  13992. for ( const key in cache ) {
  13993. const data = cache[ key ];
  13994. delete data.metadata;
  13995. values.push( data );
  13996. }
  13997. return values;
  13998. }
  13999. if ( isRoot ) {
  14000. const textures = extractFromCache( meta.textures );
  14001. const images = extractFromCache( meta.images );
  14002. const nodes = extractFromCache( meta.nodes );
  14003. if ( textures.length > 0 ) data.textures = textures;
  14004. if ( images.length > 0 ) data.images = images;
  14005. if ( nodes.length > 0 ) data.nodes = nodes;
  14006. }
  14007. return data;
  14008. }
  14009. /**
  14010. * Copies the properties of the given node material to this instance.
  14011. *
  14012. * @param {NodeMaterial} source - The material to copy.
  14013. * @return {NodeMaterial} A reference to this node material.
  14014. */
  14015. copy( source ) {
  14016. this.lightsNode = source.lightsNode;
  14017. this.envNode = source.envNode;
  14018. this.colorNode = source.colorNode;
  14019. this.normalNode = source.normalNode;
  14020. this.opacityNode = source.opacityNode;
  14021. this.backdropNode = source.backdropNode;
  14022. this.backdropAlphaNode = source.backdropAlphaNode;
  14023. this.alphaTestNode = source.alphaTestNode;
  14024. this.maskNode = source.maskNode;
  14025. this.positionNode = source.positionNode;
  14026. this.geometryNode = source.geometryNode;
  14027. this.depthNode = source.depthNode;
  14028. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14029. this.castShadowPositionNode = source.castShadowPositionNode;
  14030. this.receivedShadowNode = source.receivedShadowNode;
  14031. this.castShadowNode = source.castShadowNode;
  14032. this.outputNode = source.outputNode;
  14033. this.mrtNode = source.mrtNode;
  14034. this.fragmentNode = source.fragmentNode;
  14035. this.vertexNode = source.vertexNode;
  14036. return super.copy( source );
  14037. }
  14038. }
  14039. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14040. /**
  14041. * Node material version of {@link LineBasicMaterial}.
  14042. *
  14043. * @augments NodeMaterial
  14044. */
  14045. class LineBasicNodeMaterial extends NodeMaterial {
  14046. static get type() {
  14047. return 'LineBasicNodeMaterial';
  14048. }
  14049. /**
  14050. * Constructs a new line basic node material.
  14051. *
  14052. * @param {Object} [parameters] - The configuration parameter.
  14053. */
  14054. constructor( parameters ) {
  14055. super();
  14056. /**
  14057. * This flag can be used for type testing.
  14058. *
  14059. * @type {boolean}
  14060. * @readonly
  14061. * @default true
  14062. */
  14063. this.isLineBasicNodeMaterial = true;
  14064. this.setDefaultValues( _defaultValues$d );
  14065. this.setValues( parameters );
  14066. }
  14067. }
  14068. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14069. /**
  14070. * Node material version of {@link LineDashedMaterial}.
  14071. *
  14072. * @augments NodeMaterial
  14073. */
  14074. class LineDashedNodeMaterial extends NodeMaterial {
  14075. static get type() {
  14076. return 'LineDashedNodeMaterial';
  14077. }
  14078. /**
  14079. * Constructs a new line dashed node material.
  14080. *
  14081. * @param {Object} [parameters] - The configuration parameter.
  14082. */
  14083. constructor( parameters ) {
  14084. super();
  14085. /**
  14086. * This flag can be used for type testing.
  14087. *
  14088. * @type {boolean}
  14089. * @readonly
  14090. * @default true
  14091. */
  14092. this.isLineDashedNodeMaterial = true;
  14093. this.setDefaultValues( _defaultValues$c );
  14094. /**
  14095. * The dash offset.
  14096. *
  14097. * @type {number}
  14098. * @default 0
  14099. */
  14100. this.dashOffset = 0;
  14101. /**
  14102. * The offset of dash materials is by default inferred from the `dashOffset`
  14103. * property. This node property allows to overwrite the default
  14104. * and define the offset with a node instead.
  14105. *
  14106. * If you don't want to overwrite the offset but modify the existing
  14107. * value instead, use {@link materialLineDashOffset}.
  14108. *
  14109. * @type {?Node<float>}
  14110. * @default null
  14111. */
  14112. this.offsetNode = null;
  14113. /**
  14114. * The scale of dash materials is by default inferred from the `scale`
  14115. * property. This node property allows to overwrite the default
  14116. * and define the scale with a node instead.
  14117. *
  14118. * If you don't want to overwrite the scale but modify the existing
  14119. * value instead, use {@link materialLineScale}.
  14120. *
  14121. * @type {?Node<float>}
  14122. * @default null
  14123. */
  14124. this.dashScaleNode = null;
  14125. /**
  14126. * The dash size of dash materials is by default inferred from the `dashSize`
  14127. * property. This node property allows to overwrite the default
  14128. * and define the dash size with a node instead.
  14129. *
  14130. * If you don't want to overwrite the dash size but modify the existing
  14131. * value instead, use {@link materialLineDashSize}.
  14132. *
  14133. * @type {?Node<float>}
  14134. * @default null
  14135. */
  14136. this.dashSizeNode = null;
  14137. /**
  14138. * The gap size of dash materials is by default inferred from the `gapSize`
  14139. * property. This node property allows to overwrite the default
  14140. * and define the gap size with a node instead.
  14141. *
  14142. * If you don't want to overwrite the gap size but modify the existing
  14143. * value instead, use {@link materialLineGapSize}.
  14144. *
  14145. * @type {?Node<float>}
  14146. * @default null
  14147. */
  14148. this.gapSizeNode = null;
  14149. this.setValues( parameters );
  14150. }
  14151. /**
  14152. * Setups the dash specific node variables.
  14153. *
  14154. * @param {NodeBuilder} builder - The current node builder.
  14155. */
  14156. setupVariants( /* builder */ ) {
  14157. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14158. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14159. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14160. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14161. dashSize.assign( dashSizeNode );
  14162. gapSize.assign( gapSizeNode );
  14163. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  14164. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  14165. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  14166. }
  14167. }
  14168. let _sharedFramebuffer = null;
  14169. /**
  14170. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  14171. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  14172. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  14173. *
  14174. * @augments ViewportTextureNode
  14175. */
  14176. class ViewportSharedTextureNode extends ViewportTextureNode {
  14177. static get type() {
  14178. return 'ViewportSharedTextureNode';
  14179. }
  14180. /**
  14181. * Constructs a new viewport shared texture node.
  14182. *
  14183. * @param {Node} [uvNode=screenUV] - The uv node.
  14184. * @param {?Node} [levelNode=null] - The level node.
  14185. */
  14186. constructor( uvNode = screenUV, levelNode = null ) {
  14187. if ( _sharedFramebuffer === null ) {
  14188. _sharedFramebuffer = new FramebufferTexture();
  14189. }
  14190. super( uvNode, levelNode, _sharedFramebuffer );
  14191. }
  14192. updateReference() {
  14193. return this;
  14194. }
  14195. }
  14196. /**
  14197. * TSL function for creating a shared viewport texture node.
  14198. *
  14199. * @tsl
  14200. * @function
  14201. * @param {?Node} [uvNode=screenUV] - The uv node.
  14202. * @param {?Node} [levelNode=null] - The level node.
  14203. * @returns {ViewportSharedTextureNode}
  14204. */
  14205. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14206. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14207. /**
  14208. * This node material can be used to render lines with a size larger than one
  14209. * by representing them as instanced meshes.
  14210. *
  14211. * @augments NodeMaterial
  14212. */
  14213. class Line2NodeMaterial extends NodeMaterial {
  14214. static get type() {
  14215. return 'Line2NodeMaterial';
  14216. }
  14217. /**
  14218. * Constructs a new node material for wide line rendering.
  14219. *
  14220. * @param {Object} [parameters={}] - The configuration parameter.
  14221. */
  14222. constructor( parameters = {} ) {
  14223. super();
  14224. /**
  14225. * This flag can be used for type testing.
  14226. *
  14227. * @type {boolean}
  14228. * @readonly
  14229. * @default true
  14230. */
  14231. this.isLine2NodeMaterial = true;
  14232. this.setDefaultValues( _defaultValues$b );
  14233. /**
  14234. * Whether vertex colors should be used or not.
  14235. *
  14236. * @type {boolean}
  14237. * @default false
  14238. */
  14239. this.useColor = parameters.vertexColors;
  14240. /**
  14241. * The dash offset.
  14242. *
  14243. * @type {number}
  14244. * @default 0
  14245. */
  14246. this.dashOffset = 0;
  14247. /**
  14248. * Defines the lines color.
  14249. *
  14250. * @type {?Node<vec3>}
  14251. * @default null
  14252. */
  14253. this.lineColorNode = null;
  14254. /**
  14255. * Defines the offset.
  14256. *
  14257. * @type {?Node<float>}
  14258. * @default null
  14259. */
  14260. this.offsetNode = null;
  14261. /**
  14262. * Defines the dash scale.
  14263. *
  14264. * @type {?Node<float>}
  14265. * @default null
  14266. */
  14267. this.dashScaleNode = null;
  14268. /**
  14269. * Defines the dash size.
  14270. *
  14271. * @type {?Node<float>}
  14272. * @default null
  14273. */
  14274. this.dashSizeNode = null;
  14275. /**
  14276. * Defines the gap size.
  14277. *
  14278. * @type {?Node<float>}
  14279. * @default null
  14280. */
  14281. this.gapSizeNode = null;
  14282. /**
  14283. * Blending is set to `NoBlending` since transparency
  14284. * is not supported, yet.
  14285. *
  14286. * @type {number}
  14287. * @default 0
  14288. */
  14289. this.blending = NoBlending;
  14290. this._useDash = parameters.dashed;
  14291. this._useAlphaToCoverage = true;
  14292. this._useWorldUnits = false;
  14293. this.setValues( parameters );
  14294. }
  14295. /**
  14296. * Setups the vertex and fragment stage of this node material.
  14297. *
  14298. * @param {NodeBuilder} builder - The current node builder.
  14299. */
  14300. setup( builder ) {
  14301. const { renderer } = builder;
  14302. const useAlphaToCoverage = this._useAlphaToCoverage;
  14303. const useColor = this.useColor;
  14304. const useDash = this._useDash;
  14305. const useWorldUnits = this._useWorldUnits;
  14306. const trimSegment = Fn( ( { start, end } ) => {
  14307. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  14308. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  14309. const nearEstimate = b.mul( -0.5 ).div( a );
  14310. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  14311. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  14312. } ).setLayout( {
  14313. name: 'trimSegment',
  14314. type: 'vec4',
  14315. inputs: [
  14316. { name: 'start', type: 'vec4' },
  14317. { name: 'end', type: 'vec4' }
  14318. ]
  14319. } );
  14320. this.vertexNode = Fn( () => {
  14321. const instanceStart = attribute( 'instanceStart' );
  14322. const instanceEnd = attribute( 'instanceEnd' );
  14323. // camera space
  14324. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  14325. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  14326. if ( useDash ) {
  14327. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14328. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14329. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  14330. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  14331. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  14332. lineDistance = lineDistance.add( offsetNode );
  14333. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  14334. }
  14335. if ( useWorldUnits ) {
  14336. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  14337. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  14338. }
  14339. const aspect = viewport.z.div( viewport.w );
  14340. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  14341. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  14342. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  14343. // perhaps there is a more elegant solution -- WestLangley
  14344. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  14345. If( perspective, () => {
  14346. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  14347. end.assign( trimSegment( { start: start, end: end } ) );
  14348. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  14349. start.assign( trimSegment( { start: end, end: start } ) );
  14350. } );
  14351. } );
  14352. // clip space
  14353. const clipStart = cameraProjectionMatrix.mul( start );
  14354. const clipEnd = cameraProjectionMatrix.mul( end );
  14355. // ndc space
  14356. const ndcStart = clipStart.xyz.div( clipStart.w );
  14357. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  14358. // direction
  14359. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  14360. // account for clip-space aspect ratio
  14361. dir.x.assign( dir.x.mul( aspect ) );
  14362. dir.assign( dir.normalize() );
  14363. const clip = vec4().toVar();
  14364. if ( useWorldUnits ) {
  14365. // get the offset direction as perpendicular to the view vector
  14366. const worldDir = end.xyz.sub( start.xyz ).normalize();
  14367. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  14368. const worldUp = worldDir.cross( tmpFwd ).normalize();
  14369. const worldFwd = worldDir.cross( worldUp );
  14370. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  14371. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  14372. // height offset
  14373. const hw = materialLineWidth.mul( 0.5 );
  14374. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  14375. // don't extend the line if we're rendering dashes because we
  14376. // won't be rendering the endcaps
  14377. if ( ! useDash ) {
  14378. // cap extension
  14379. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  14380. // add width to the box
  14381. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  14382. // endcaps
  14383. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  14384. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  14385. } );
  14386. }
  14387. // project the worldpos
  14388. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  14389. // shift the depth of the projected points so the line
  14390. // segments overlap neatly
  14391. const clipPose = vec3().toVar();
  14392. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  14393. clip.z.assign( clipPose.z.mul( clip.w ) );
  14394. } else {
  14395. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  14396. // undo aspect ratio adjustment
  14397. dir.x.assign( dir.x.div( aspect ) );
  14398. offset.x.assign( offset.x.div( aspect ) );
  14399. // sign flip
  14400. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  14401. // endcaps
  14402. If( positionGeometry.y.lessThan( 0.0 ), () => {
  14403. offset.assign( offset.sub( dir ) );
  14404. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  14405. offset.assign( offset.add( dir ) );
  14406. } );
  14407. // adjust for linewidth
  14408. offset.assign( offset.mul( materialLineWidth ) );
  14409. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  14410. offset.assign( offset.div( viewport.w ) );
  14411. // select end
  14412. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  14413. // back to clip space
  14414. offset.assign( offset.mul( clip.w ) );
  14415. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  14416. }
  14417. return clip;
  14418. } )();
  14419. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  14420. const p13 = p1.sub( p3 );
  14421. const p43 = p4.sub( p3 );
  14422. const p21 = p2.sub( p1 );
  14423. const d1343 = p13.dot( p43 );
  14424. const d4321 = p43.dot( p21 );
  14425. const d1321 = p13.dot( p21 );
  14426. const d4343 = p43.dot( p43 );
  14427. const d2121 = p21.dot( p21 );
  14428. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  14429. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  14430. const mua = numer.div( denom ).clamp();
  14431. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  14432. return vec2( mua, mub );
  14433. } );
  14434. this.colorNode = Fn( () => {
  14435. const vUv = uv$1();
  14436. if ( useDash ) {
  14437. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14438. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14439. dashSize.assign( dashSizeNode );
  14440. gapSize.assign( gapSizeNode );
  14441. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  14442. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  14443. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  14444. }
  14445. const alpha = float( 1 ).toVar( 'alpha' );
  14446. if ( useWorldUnits ) {
  14447. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  14448. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  14449. // Find the closest points on the view ray and the line segment
  14450. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  14451. const lineDir = worldEnd.sub( worldStart );
  14452. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  14453. const p1 = worldStart.add( lineDir.mul( params.x ) );
  14454. const p2 = rayEnd.mul( params.y );
  14455. const delta = p1.sub( p2 );
  14456. const len = delta.length();
  14457. const norm = len.div( materialLineWidth );
  14458. if ( ! useDash ) {
  14459. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14460. const dnorm = norm.fwidth();
  14461. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  14462. } else {
  14463. norm.greaterThan( 0.5 ).discard();
  14464. }
  14465. }
  14466. } else {
  14467. // round endcaps
  14468. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14469. const a = vUv.x;
  14470. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14471. const len2 = a.mul( a ).add( b.mul( b ) );
  14472. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  14473. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14474. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  14475. } );
  14476. } else {
  14477. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14478. const a = vUv.x;
  14479. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14480. const len2 = a.mul( a ).add( b.mul( b ) );
  14481. len2.greaterThan( 1.0 ).discard();
  14482. } );
  14483. }
  14484. }
  14485. let lineColorNode;
  14486. if ( this.lineColorNode ) {
  14487. lineColorNode = this.lineColorNode;
  14488. } else {
  14489. if ( useColor ) {
  14490. const instanceColorStart = attribute( 'instanceColorStart' );
  14491. const instanceColorEnd = attribute( 'instanceColorEnd' );
  14492. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  14493. lineColorNode = instanceColor.mul( materialColor );
  14494. } else {
  14495. lineColorNode = materialColor;
  14496. }
  14497. }
  14498. return vec4( lineColorNode, alpha );
  14499. } )();
  14500. if ( this.transparent ) {
  14501. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14502. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  14503. }
  14504. super.setup( builder );
  14505. }
  14506. /**
  14507. * Whether the lines should sized in world units or not.
  14508. * When set to `false` the unit is pixel.
  14509. *
  14510. * @type {boolean}
  14511. * @default false
  14512. */
  14513. get worldUnits() {
  14514. return this._useWorldUnits;
  14515. }
  14516. set worldUnits( value ) {
  14517. if ( this._useWorldUnits !== value ) {
  14518. this._useWorldUnits = value;
  14519. this.needsUpdate = true;
  14520. }
  14521. }
  14522. /**
  14523. * Whether the lines should be dashed or not.
  14524. *
  14525. * @type {boolean}
  14526. * @default false
  14527. */
  14528. get dashed() {
  14529. return this._useDash;
  14530. }
  14531. set dashed( value ) {
  14532. if ( this._useDash !== value ) {
  14533. this._useDash = value;
  14534. this.needsUpdate = true;
  14535. }
  14536. }
  14537. /**
  14538. * Whether alpha to coverage should be used or not.
  14539. *
  14540. * @type {boolean}
  14541. * @default true
  14542. */
  14543. get alphaToCoverage() {
  14544. return this._useAlphaToCoverage;
  14545. }
  14546. set alphaToCoverage( value ) {
  14547. if ( this._useAlphaToCoverage !== value ) {
  14548. this._useAlphaToCoverage = value;
  14549. this.needsUpdate = true;
  14550. }
  14551. }
  14552. }
  14553. /**
  14554. * Packs a direction vector into a color value.
  14555. *
  14556. * @tsl
  14557. * @function
  14558. * @param {Node<vec3>} node - The direction to pack.
  14559. * @return {Node<vec3>} The color.
  14560. */
  14561. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  14562. /**
  14563. * Unpacks a color value into a direction vector.
  14564. *
  14565. * @tsl
  14566. * @function
  14567. * @param {Node<vec3>} node - The color to unpack.
  14568. * @return {Node<vec3>} The direction.
  14569. */
  14570. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  14571. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  14572. /**
  14573. * Node material version of {@link MeshNormalMaterial}.
  14574. *
  14575. * @augments NodeMaterial
  14576. */
  14577. class MeshNormalNodeMaterial extends NodeMaterial {
  14578. static get type() {
  14579. return 'MeshNormalNodeMaterial';
  14580. }
  14581. /**
  14582. * Constructs a new mesh normal node material.
  14583. *
  14584. * @param {Object} [parameters] - The configuration parameter.
  14585. */
  14586. constructor( parameters ) {
  14587. super();
  14588. /**
  14589. * This flag can be used for type testing.
  14590. *
  14591. * @type {boolean}
  14592. * @readonly
  14593. * @default true
  14594. */
  14595. this.isMeshNormalNodeMaterial = true;
  14596. this.setDefaultValues( _defaultValues$a );
  14597. this.setValues( parameters );
  14598. }
  14599. /**
  14600. * Overwrites the default implementation by computing the diffuse color
  14601. * based on the normal data.
  14602. */
  14603. setupDiffuseColor() {
  14604. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14605. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  14606. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  14607. }
  14608. }
  14609. /**
  14610. * TSL function for creating an equirect uv node.
  14611. *
  14612. * Can be used to compute texture coordinates for projecting an
  14613. * equirectangular texture onto a mesh for using it as the scene's
  14614. * background.
  14615. *
  14616. * ```js
  14617. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  14618. * ```
  14619. *
  14620. * @tsl
  14621. * @function
  14622. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  14623. * @returns {Node<vec2>}
  14624. */
  14625. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  14626. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  14627. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  14628. return vec2( u, v );
  14629. } );
  14630. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  14631. /**
  14632. * This class represents a cube render target. It is a special version
  14633. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  14634. *
  14635. * @augments WebGLCubeRenderTarget
  14636. */
  14637. class CubeRenderTarget extends WebGLCubeRenderTarget {
  14638. /**
  14639. * Constructs a new cube render target.
  14640. *
  14641. * @param {number} [size=1] - The size of the render target.
  14642. * @param {RenderTarget~Options} [options] - The configuration object.
  14643. */
  14644. constructor( size = 1, options = {} ) {
  14645. super( size, options );
  14646. /**
  14647. * This flag can be used for type testing.
  14648. *
  14649. * @type {boolean}
  14650. * @readonly
  14651. * @default true
  14652. */
  14653. this.isCubeRenderTarget = true;
  14654. }
  14655. /**
  14656. * Converts the given equirectangular texture to a cube map.
  14657. *
  14658. * @param {Renderer} renderer - The renderer.
  14659. * @param {Texture} texture - The equirectangular texture.
  14660. * @return {CubeRenderTarget} A reference to this cube render target.
  14661. */
  14662. fromEquirectangularTexture( renderer, texture$1 ) {
  14663. const currentMinFilter = texture$1.minFilter;
  14664. const currentGenerateMipmaps = texture$1.generateMipmaps;
  14665. texture$1.generateMipmaps = true;
  14666. this.texture.type = texture$1.type;
  14667. this.texture.colorSpace = texture$1.colorSpace;
  14668. this.texture.generateMipmaps = texture$1.generateMipmaps;
  14669. this.texture.minFilter = texture$1.minFilter;
  14670. this.texture.magFilter = texture$1.magFilter;
  14671. const geometry = new BoxGeometry( 5, 5, 5 );
  14672. const uvNode = equirectUV( positionWorldDirection );
  14673. const material = new NodeMaterial();
  14674. material.colorNode = texture( texture$1, uvNode, 0 );
  14675. material.side = BackSide;
  14676. material.blending = NoBlending;
  14677. const mesh = new Mesh( geometry, material );
  14678. const scene = new Scene();
  14679. scene.add( mesh );
  14680. // Avoid blurred poles
  14681. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  14682. const camera = new CubeCamera( 1, 10, this );
  14683. const currentMRT = renderer.getMRT();
  14684. renderer.setMRT( null );
  14685. camera.update( renderer, scene );
  14686. renderer.setMRT( currentMRT );
  14687. texture$1.minFilter = currentMinFilter;
  14688. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  14689. mesh.geometry.dispose();
  14690. mesh.material.dispose();
  14691. return this;
  14692. }
  14693. }
  14694. const _cache$1 = new WeakMap();
  14695. /**
  14696. * This node can be used to automatically convert environment maps in the
  14697. * equirectangular format into the cube map format.
  14698. *
  14699. * @augments TempNode
  14700. */
  14701. class CubeMapNode extends TempNode {
  14702. static get type() {
  14703. return 'CubeMapNode';
  14704. }
  14705. /**
  14706. * Constructs a new cube map node.
  14707. *
  14708. * @param {Node} envNode - The node representing the environment map.
  14709. */
  14710. constructor( envNode ) {
  14711. super( 'vec3' );
  14712. /**
  14713. * The node representing the environment map.
  14714. *
  14715. * @type {Node}
  14716. */
  14717. this.envNode = envNode;
  14718. /**
  14719. * A reference to the internal cube texture.
  14720. *
  14721. * @private
  14722. * @type {?CubeTexture}
  14723. * @default null
  14724. */
  14725. this._cubeTexture = null;
  14726. /**
  14727. * A reference to the internal cube texture node.
  14728. *
  14729. * @private
  14730. * @type {CubeTextureNode}
  14731. */
  14732. this._cubeTextureNode = cubeTexture( null );
  14733. const defaultTexture = new CubeTexture();
  14734. defaultTexture.isRenderTargetTexture = true;
  14735. /**
  14736. * A default cube texture that acts as a placeholder.
  14737. * It is used when the conversion from equirectangular to cube
  14738. * map has not finished yet for a given texture.
  14739. *
  14740. * @private
  14741. * @type {CubeTexture}
  14742. */
  14743. this._defaultTexture = defaultTexture;
  14744. /**
  14745. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  14746. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  14747. *
  14748. * @type {string}
  14749. * @default 'render'
  14750. */
  14751. this.updateBeforeType = NodeUpdateType.RENDER;
  14752. }
  14753. updateBefore( frame ) {
  14754. const { renderer, material } = frame;
  14755. const envNode = this.envNode;
  14756. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14757. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14758. if ( texture && texture.isTexture ) {
  14759. const mapping = texture.mapping;
  14760. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  14761. // check for converted cubemap map
  14762. if ( _cache$1.has( texture ) ) {
  14763. const cubeMap = _cache$1.get( texture );
  14764. mapTextureMapping( cubeMap, texture.mapping );
  14765. this._cubeTexture = cubeMap;
  14766. } else {
  14767. // create cube map from equirectangular map
  14768. const image = texture.image;
  14769. if ( isEquirectangularMapReady$1( image ) ) {
  14770. const renderTarget = new CubeRenderTarget( image.height );
  14771. renderTarget.fromEquirectangularTexture( renderer, texture );
  14772. mapTextureMapping( renderTarget.texture, texture.mapping );
  14773. this._cubeTexture = renderTarget.texture;
  14774. _cache$1.set( texture, renderTarget.texture );
  14775. texture.addEventListener( 'dispose', onTextureDispose );
  14776. } else {
  14777. // default cube texture as fallback when equirectangular texture is not yet loaded
  14778. this._cubeTexture = this._defaultTexture;
  14779. }
  14780. }
  14781. //
  14782. this._cubeTextureNode.value = this._cubeTexture;
  14783. } else {
  14784. // envNode already refers to a cube map
  14785. this._cubeTextureNode = this.envNode;
  14786. }
  14787. }
  14788. }
  14789. }
  14790. setup( builder ) {
  14791. this.updateBefore( builder );
  14792. return this._cubeTextureNode;
  14793. }
  14794. }
  14795. /**
  14796. * Returns true if the given equirectangular image has been fully loaded
  14797. * and is ready for further processing.
  14798. *
  14799. * @private
  14800. * @param {Image} image - The equirectangular image to check.
  14801. * @return {boolean} Whether the image is ready or not.
  14802. */
  14803. function isEquirectangularMapReady$1( image ) {
  14804. if ( image === null || image === undefined ) return false;
  14805. return image.height > 0;
  14806. }
  14807. /**
  14808. * This function is executed when `dispose()` is called on the equirectangular
  14809. * texture. In this case, the generated cube map with its render target
  14810. * is deleted as well.
  14811. *
  14812. * @private
  14813. * @param {Object} event - The event object.
  14814. */
  14815. function onTextureDispose( event ) {
  14816. const texture = event.target;
  14817. texture.removeEventListener( 'dispose', onTextureDispose );
  14818. const renderTarget = _cache$1.get( texture );
  14819. if ( renderTarget !== undefined ) {
  14820. _cache$1.delete( texture );
  14821. renderTarget.dispose();
  14822. }
  14823. }
  14824. /**
  14825. * This function makes sure the generated cube map uses the correct
  14826. * texture mapping that corresponds to the equirectangular original.
  14827. *
  14828. * @private
  14829. * @param {Texture} texture - The cube texture.
  14830. * @param {number} mapping - The original texture mapping.
  14831. */
  14832. function mapTextureMapping( texture, mapping ) {
  14833. if ( mapping === EquirectangularReflectionMapping ) {
  14834. texture.mapping = CubeReflectionMapping;
  14835. } else if ( mapping === EquirectangularRefractionMapping ) {
  14836. texture.mapping = CubeRefractionMapping;
  14837. }
  14838. }
  14839. /**
  14840. * TSL function for creating a cube map node.
  14841. *
  14842. * @tsl
  14843. * @function
  14844. * @param {Node} envNode - The node representing the environment map.
  14845. * @returns {CubeMapNode}
  14846. */
  14847. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  14848. /**
  14849. * Represents a basic model for Image-based lighting (IBL). The environment
  14850. * is defined via environment maps in the equirectangular or cube map format.
  14851. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  14852. * or {@link MeshPhongNodeMaterial}.
  14853. *
  14854. * @augments LightingNode
  14855. */
  14856. class BasicEnvironmentNode extends LightingNode {
  14857. static get type() {
  14858. return 'BasicEnvironmentNode';
  14859. }
  14860. /**
  14861. * Constructs a new basic environment node.
  14862. *
  14863. * @param {Node} [envNode=null] - A node representing the environment.
  14864. */
  14865. constructor( envNode = null ) {
  14866. super();
  14867. /**
  14868. * A node representing the environment.
  14869. *
  14870. * @type {Node}
  14871. * @default null
  14872. */
  14873. this.envNode = envNode;
  14874. }
  14875. setup( builder ) {
  14876. // environment property is used in the finish() method of BasicLightingModel
  14877. builder.context.environment = cubeMapNode( this.envNode );
  14878. }
  14879. }
  14880. /**
  14881. * A specific version of {@link IrradianceNode} that is only relevant
  14882. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  14883. * requires a special scaling factor for the light map.
  14884. *
  14885. * @augments LightingNode
  14886. */
  14887. class BasicLightMapNode extends LightingNode {
  14888. static get type() {
  14889. return 'BasicLightMapNode';
  14890. }
  14891. /**
  14892. * Constructs a new basic light map node.
  14893. *
  14894. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  14895. */
  14896. constructor( lightMapNode = null ) {
  14897. super();
  14898. /**
  14899. * The light map node.
  14900. *
  14901. * @type {?Node<vec3>}
  14902. */
  14903. this.lightMapNode = lightMapNode;
  14904. }
  14905. setup( builder ) {
  14906. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  14907. const RECIPROCAL_PI = float( 1 / Math.PI );
  14908. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  14909. }
  14910. }
  14911. /**
  14912. * Abstract class for implementing lighting models. The module defines
  14913. * multiple methods that concrete lighting models can implement. These
  14914. * methods are executed at different points during the light evaluation
  14915. * process.
  14916. */
  14917. class LightingModel {
  14918. /**
  14919. * This method is intended for setting up lighting model and context data
  14920. * which are later used in the evaluation process.
  14921. *
  14922. * @abstract
  14923. * @param {NodeBuilder} builder - The current node builder.
  14924. */
  14925. start( builder ) {
  14926. // lights ( direct )
  14927. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  14928. // indirect
  14929. this.indirect( builder );
  14930. }
  14931. /**
  14932. * This method is intended for executing final tasks like final updates
  14933. * to the outgoing light.
  14934. *
  14935. * @abstract
  14936. * @param {NodeBuilder} builder - The current node builder.
  14937. */
  14938. finish( /*builder*/ ) { }
  14939. /**
  14940. * This method is intended for implementing the direct light term and
  14941. * executed during the build process of directional, point and spot light nodes.
  14942. *
  14943. * @abstract
  14944. * @param {Object} lightData - The light data.
  14945. * @param {NodeBuilder} builder - The current node builder.
  14946. */
  14947. direct( /*lightData, builder*/ ) { }
  14948. /**
  14949. * This method is intended for implementing the direct light term for
  14950. * rect area light nodes.
  14951. *
  14952. * @abstract
  14953. * @param {Object} lightData - The light data.
  14954. * @param {NodeBuilder} builder - The current node builder.
  14955. */
  14956. directRectArea( /*lightData, builder*/ ) {}
  14957. /**
  14958. * This method is intended for implementing the indirect light term.
  14959. *
  14960. * @abstract
  14961. * @param {NodeBuilder} builder - The current node builder.
  14962. */
  14963. indirect( /*builder*/ ) { }
  14964. /**
  14965. * This method is intended for implementing the ambient occlusion term.
  14966. * Unlike other methods, this method must be called manually by the lighting
  14967. * model in its indirect term.
  14968. *
  14969. * @abstract
  14970. * @param {NodeBuilder} builder - The current node builder.
  14971. */
  14972. ambientOcclusion( /*input, stack, builder*/ ) { }
  14973. }
  14974. /**
  14975. * Represents the lighting model for unlit materials. The only light contribution
  14976. * is baked indirect lighting modulated with ambient occlusion and the material's
  14977. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  14978. *
  14979. * @augments LightingModel
  14980. */
  14981. class BasicLightingModel extends LightingModel {
  14982. /**
  14983. * Constructs a new basic lighting model.
  14984. */
  14985. constructor() {
  14986. super();
  14987. }
  14988. /**
  14989. * Implements the baked indirect lighting with its modulation.
  14990. *
  14991. * @param {NodeBuilder} builder - The current node builder.
  14992. */
  14993. indirect( { context } ) {
  14994. const ambientOcclusion = context.ambientOcclusion;
  14995. const reflectedLight = context.reflectedLight;
  14996. const irradianceLightMap = context.irradianceLightMap;
  14997. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  14998. // accumulation (baked indirect lighting only)
  14999. if ( irradianceLightMap ) {
  15000. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15001. } else {
  15002. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15003. }
  15004. // modulation
  15005. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15006. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15007. }
  15008. /**
  15009. * Implements the environment mapping.
  15010. *
  15011. * @param {NodeBuilder} builder - The current node builder.
  15012. */
  15013. finish( builder ) {
  15014. const { material, context } = builder;
  15015. const outgoingLight = context.outgoingLight;
  15016. const envNode = builder.context.environment;
  15017. if ( envNode ) {
  15018. switch ( material.combine ) {
  15019. case MultiplyOperation:
  15020. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15021. break;
  15022. case MixOperation:
  15023. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15024. break;
  15025. case AddOperation:
  15026. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15027. break;
  15028. default:
  15029. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  15030. break;
  15031. }
  15032. }
  15033. }
  15034. }
  15035. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15036. /**
  15037. * Node material version of {@link MeshBasicMaterial}.
  15038. *
  15039. * @augments NodeMaterial
  15040. */
  15041. class MeshBasicNodeMaterial extends NodeMaterial {
  15042. static get type() {
  15043. return 'MeshBasicNodeMaterial';
  15044. }
  15045. /**
  15046. * Constructs a new mesh basic node material.
  15047. *
  15048. * @param {Object} [parameters] - The configuration parameter.
  15049. */
  15050. constructor( parameters ) {
  15051. super();
  15052. /**
  15053. * This flag can be used for type testing.
  15054. *
  15055. * @type {boolean}
  15056. * @readonly
  15057. * @default true
  15058. */
  15059. this.isMeshBasicNodeMaterial = true;
  15060. /**
  15061. * Although the basic material is by definition unlit, we set
  15062. * this property to `true` since we use a lighting model to compute
  15063. * the outgoing light of the fragment shader.
  15064. *
  15065. * @type {boolean}
  15066. * @default true
  15067. */
  15068. this.lights = true;
  15069. this.setDefaultValues( _defaultValues$9 );
  15070. this.setValues( parameters );
  15071. }
  15072. /**
  15073. * Basic materials are not affected by normal and bump maps so we
  15074. * return by default {@link normalViewGeometry}.
  15075. *
  15076. * @return {Node<vec3>} The normal node.
  15077. */
  15078. setupNormal() {
  15079. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15080. }
  15081. /**
  15082. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15083. * to implement the default environment mapping.
  15084. *
  15085. * @param {NodeBuilder} builder - The current node builder.
  15086. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15087. */
  15088. setupEnvironment( builder ) {
  15089. const envNode = super.setupEnvironment( builder );
  15090. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15091. }
  15092. /**
  15093. * This method must be overwritten since light maps are evaluated
  15094. * with a special scaling factor for basic materials.
  15095. *
  15096. * @param {NodeBuilder} builder - The current node builder.
  15097. * @return {?BasicLightMapNode<vec3>} The light map node.
  15098. */
  15099. setupLightMap( builder ) {
  15100. let node = null;
  15101. if ( builder.material.lightMap ) {
  15102. node = new BasicLightMapNode( materialLightMap );
  15103. }
  15104. return node;
  15105. }
  15106. /**
  15107. * The material overwrites this method because `lights` is set to `true` but
  15108. * we still want to return the diffuse color as the outgoing light.
  15109. *
  15110. * @return {Node<vec3>} The outgoing light node.
  15111. */
  15112. setupOutgoingLight() {
  15113. return diffuseColor.rgb;
  15114. }
  15115. /**
  15116. * Setups the lighting model.
  15117. *
  15118. * @return {BasicLightingModel} The lighting model.
  15119. */
  15120. setupLightingModel() {
  15121. return new BasicLightingModel();
  15122. }
  15123. }
  15124. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15125. // Original approximation by Christophe Schlick '94
  15126. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15127. // Optimized variant (presented by Epic at SIGGRAPH '13)
  15128. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  15129. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  15130. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  15131. } ); // validated
  15132. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  15133. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  15134. } ); // validated
  15135. const G_BlinnPhong_Implicit = () => float( 0.25 );
  15136. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  15137. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  15138. } );
  15139. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15140. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15141. const dotNH = normalView.dot( halfDir ).clamp();
  15142. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15143. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  15144. const G = G_BlinnPhong_Implicit();
  15145. const D = D_BlinnPhong( { dotNH } );
  15146. return F.mul( G ).mul( D );
  15147. } );
  15148. /**
  15149. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  15150. *
  15151. * @augments BasicLightingModel
  15152. */
  15153. class PhongLightingModel extends BasicLightingModel {
  15154. /**
  15155. * Constructs a new phong lighting model.
  15156. *
  15157. * @param {boolean} [specular=true] - Whether specular is supported or not.
  15158. */
  15159. constructor( specular = true ) {
  15160. super();
  15161. /**
  15162. * Whether specular is supported or not. Set this to `false` if you are
  15163. * looking for a Lambert-like material meaning a material for non-shiny
  15164. * surfaces, without specular highlights.
  15165. *
  15166. * @type {boolean}
  15167. * @default true
  15168. */
  15169. this.specular = specular;
  15170. }
  15171. /**
  15172. * Implements the direct lighting. The specular portion is optional an can be controlled
  15173. * with the {@link PhongLightingModel#specular} flag.
  15174. *
  15175. * @param {Object} lightData - The light data.
  15176. */
  15177. direct( { lightDirection, lightColor, reflectedLight } ) {
  15178. const dotNL = normalView.dot( lightDirection ).clamp();
  15179. const irradiance = dotNL.mul( lightColor );
  15180. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15181. if ( this.specular === true ) {
  15182. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  15183. }
  15184. }
  15185. /**
  15186. * Implements the indirect lighting.
  15187. *
  15188. * @param {NodeBuilder} builder - The current node builder.
  15189. */
  15190. indirect( builder ) {
  15191. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  15192. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15193. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15194. }
  15195. }
  15196. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  15197. /**
  15198. * Node material version of {@link MeshLambertMaterial}.
  15199. *
  15200. * @augments NodeMaterial
  15201. */
  15202. class MeshLambertNodeMaterial extends NodeMaterial {
  15203. static get type() {
  15204. return 'MeshLambertNodeMaterial';
  15205. }
  15206. /**
  15207. * Constructs a new mesh lambert node material.
  15208. *
  15209. * @param {Object} [parameters] - The configuration parameter.
  15210. */
  15211. constructor( parameters ) {
  15212. super();
  15213. /**
  15214. * This flag can be used for type testing.
  15215. *
  15216. * @type {boolean}
  15217. * @readonly
  15218. * @default true
  15219. */
  15220. this.isMeshLambertNodeMaterial = true;
  15221. /**
  15222. * Set to `true` because lambert materials react on lights.
  15223. *
  15224. * @type {boolean}
  15225. * @default true
  15226. */
  15227. this.lights = true;
  15228. this.setDefaultValues( _defaultValues$8 );
  15229. this.setValues( parameters );
  15230. }
  15231. /**
  15232. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15233. * to implement the default environment mapping.
  15234. *
  15235. * @param {NodeBuilder} builder - The current node builder.
  15236. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15237. */
  15238. setupEnvironment( builder ) {
  15239. const envNode = super.setupEnvironment( builder );
  15240. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15241. }
  15242. /**
  15243. * Setups the lighting model.
  15244. *
  15245. * @return {PhongLightingModel} The lighting model.
  15246. */
  15247. setupLightingModel( /*builder*/ ) {
  15248. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  15249. }
  15250. }
  15251. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  15252. /**
  15253. * Node material version of {@link MeshPhongMaterial}.
  15254. *
  15255. * @augments NodeMaterial
  15256. */
  15257. class MeshPhongNodeMaterial extends NodeMaterial {
  15258. static get type() {
  15259. return 'MeshPhongNodeMaterial';
  15260. }
  15261. /**
  15262. * Constructs a new mesh lambert node material.
  15263. *
  15264. * @param {Object} [parameters] - The configuration parameter.
  15265. */
  15266. constructor( parameters ) {
  15267. super();
  15268. /**
  15269. * This flag can be used for type testing.
  15270. *
  15271. * @type {boolean}
  15272. * @readonly
  15273. * @default true
  15274. */
  15275. this.isMeshPhongNodeMaterial = true;
  15276. /**
  15277. * Set to `true` because phong materials react on lights.
  15278. *
  15279. * @type {boolean}
  15280. * @default true
  15281. */
  15282. this.lights = true;
  15283. /**
  15284. * The shininess of phong materials is by default inferred from the `shininess`
  15285. * property. This node property allows to overwrite the default
  15286. * and define the shininess with a node instead.
  15287. *
  15288. * If you don't want to overwrite the shininess but modify the existing
  15289. * value instead, use {@link materialShininess}.
  15290. *
  15291. * @type {?Node<float>}
  15292. * @default null
  15293. */
  15294. this.shininessNode = null;
  15295. /**
  15296. * The specular color of phong materials is by default inferred from the
  15297. * `specular` property. This node property allows to overwrite the default
  15298. * and define the specular color with a node instead.
  15299. *
  15300. * If you don't want to overwrite the specular color but modify the existing
  15301. * value instead, use {@link materialSpecular}.
  15302. *
  15303. * @type {?Node<vec3>}
  15304. * @default null
  15305. */
  15306. this.specularNode = null;
  15307. this.setDefaultValues( _defaultValues$7 );
  15308. this.setValues( parameters );
  15309. }
  15310. /**
  15311. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15312. * to implement the default environment mapping.
  15313. *
  15314. * @param {NodeBuilder} builder - The current node builder.
  15315. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15316. */
  15317. setupEnvironment( builder ) {
  15318. const envNode = super.setupEnvironment( builder );
  15319. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15320. }
  15321. /**
  15322. * Setups the lighting model.
  15323. *
  15324. * @return {PhongLightingModel} The lighting model.
  15325. */
  15326. setupLightingModel( /*builder*/ ) {
  15327. return new PhongLightingModel();
  15328. }
  15329. /**
  15330. * Setups the phong specific node variables.
  15331. *
  15332. * @param {NodeBuilder} builder - The current node builder.
  15333. */
  15334. setupVariants( /*builder*/ ) {
  15335. // SHININESS
  15336. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15337. shininess.assign( shininessNode );
  15338. // SPECULAR COLOR
  15339. const specularNode = this.specularNode || materialSpecular;
  15340. specularColor.assign( specularNode );
  15341. }
  15342. copy( source ) {
  15343. this.shininessNode = source.shininessNode;
  15344. this.specularNode = source.specularNode;
  15345. return super.copy( source );
  15346. }
  15347. }
  15348. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  15349. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  15350. return float( 0 );
  15351. }
  15352. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  15353. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  15354. return geometryRoughness;
  15355. } );
  15356. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  15357. const { roughness } = inputs;
  15358. const geometryRoughness = getGeometryRoughness();
  15359. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  15360. roughnessFactor = roughnessFactor.add( geometryRoughness );
  15361. roughnessFactor = roughnessFactor.min( 1.0 );
  15362. return roughnessFactor;
  15363. } );
  15364. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  15365. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  15366. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  15367. const a2 = alpha.pow2();
  15368. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  15369. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  15370. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  15371. } ).setLayout( {
  15372. name: 'V_GGX_SmithCorrelated',
  15373. type: 'float',
  15374. inputs: [
  15375. { name: 'alpha', type: 'float' },
  15376. { name: 'dotNL', type: 'float' },
  15377. { name: 'dotNV', type: 'float' }
  15378. ]
  15379. } ); // validated
  15380. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15381. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  15382. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  15383. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  15384. const v = div( 0.5, gv.add( gl ) );
  15385. return v.saturate();
  15386. } ).setLayout( {
  15387. name: 'V_GGX_SmithCorrelated_Anisotropic',
  15388. type: 'float',
  15389. inputs: [
  15390. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15391. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15392. { name: 'dotTV', type: 'float', qualifier: 'in' },
  15393. { name: 'dotBV', type: 'float', qualifier: 'in' },
  15394. { name: 'dotTL', type: 'float', qualifier: 'in' },
  15395. { name: 'dotBL', type: 'float', qualifier: 'in' },
  15396. { name: 'dotNV', type: 'float', qualifier: 'in' },
  15397. { name: 'dotNL', type: 'float', qualifier: 'in' }
  15398. ]
  15399. } );
  15400. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  15401. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  15402. // alpha is "roughness squared" in Disney’s reparameterization
  15403. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  15404. const a2 = alpha.pow2();
  15405. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  15406. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  15407. } ).setLayout( {
  15408. name: 'D_GGX',
  15409. type: 'float',
  15410. inputs: [
  15411. { name: 'alpha', type: 'float' },
  15412. { name: 'dotNH', type: 'float' }
  15413. ]
  15414. } ); // validated
  15415. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  15416. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15417. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  15418. const a2 = alphaT.mul( alphaB );
  15419. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  15420. const v2 = v.dot( v );
  15421. const w2 = a2.div( v2 );
  15422. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  15423. } ).setLayout( {
  15424. name: 'D_GGX_Anisotropic',
  15425. type: 'float',
  15426. inputs: [
  15427. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15428. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15429. { name: 'dotNH', type: 'float', qualifier: 'in' },
  15430. { name: 'dotTH', type: 'float', qualifier: 'in' },
  15431. { name: 'dotBH', type: 'float', qualifier: 'in' }
  15432. ]
  15433. } );
  15434. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  15435. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  15436. const alpha = roughness.pow2(); // UE4's roughness
  15437. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15438. const dotNL = normalView$1.dot( lightDirection ).clamp();
  15439. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15440. const dotNH = normalView$1.dot( halfDir ).clamp();
  15441. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15442. let F = F_Schlick( { f0, f90, dotVH } );
  15443. let V, D;
  15444. if ( defined( USE_IRIDESCENCE ) ) {
  15445. F = iridescence.mix( F, f );
  15446. }
  15447. if ( defined( USE_ANISOTROPY ) ) {
  15448. const dotTL = anisotropyT.dot( lightDirection );
  15449. const dotTV = anisotropyT.dot( positionViewDirection );
  15450. const dotTH = anisotropyT.dot( halfDir );
  15451. const dotBL = anisotropyB.dot( lightDirection );
  15452. const dotBV = anisotropyB.dot( positionViewDirection );
  15453. const dotBH = anisotropyB.dot( halfDir );
  15454. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  15455. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  15456. } else {
  15457. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  15458. D = D_GGX( { alpha, dotNH } );
  15459. }
  15460. return F.mul( V ).mul( D );
  15461. } ); // validated
  15462. // Analytical approximation of the DFG LUT, one half of the
  15463. // split-sum approximation used in indirect specular lighting.
  15464. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  15465. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  15466. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  15467. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  15468. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  15469. const r = roughness.mul( c0 ).add( c1 );
  15470. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  15471. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  15472. return fab;
  15473. } ).setLayout( {
  15474. name: 'DFGApprox',
  15475. type: 'vec2',
  15476. inputs: [
  15477. { name: 'roughness', type: 'float' },
  15478. { name: 'dotNV', type: 'vec3' }
  15479. ]
  15480. } );
  15481. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  15482. const { dotNV, specularColor, specularF90, roughness } = inputs;
  15483. const fab = DFGApprox( { dotNV, roughness } );
  15484. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15485. } );
  15486. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  15487. const x = dotVH.oneMinus().saturate();
  15488. const x2 = x.mul( x );
  15489. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  15490. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  15491. } ).setLayout( {
  15492. name: 'Schlick_to_F0',
  15493. type: 'vec3',
  15494. inputs: [
  15495. { name: 'f', type: 'vec3' },
  15496. { name: 'f90', type: 'float' },
  15497. { name: 'dotVH', type: 'float' }
  15498. ]
  15499. } );
  15500. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15501. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  15502. const alpha = roughness.pow2();
  15503. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  15504. const invAlpha = float( 1.0 ).div( alpha );
  15505. const cos2h = dotNH.pow2();
  15506. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  15507. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  15508. } ).setLayout( {
  15509. name: 'D_Charlie',
  15510. type: 'float',
  15511. inputs: [
  15512. { name: 'roughness', type: 'float' },
  15513. { name: 'dotNH', type: 'float' }
  15514. ]
  15515. } );
  15516. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15517. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  15518. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  15519. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  15520. } ).setLayout( {
  15521. name: 'V_Neubelt',
  15522. type: 'float',
  15523. inputs: [
  15524. { name: 'dotNV', type: 'float' },
  15525. { name: 'dotNL', type: 'float' }
  15526. ]
  15527. } );
  15528. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15529. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15530. const dotNL = normalView.dot( lightDirection ).clamp();
  15531. const dotNV = normalView.dot( positionViewDirection ).clamp();
  15532. const dotNH = normalView.dot( halfDir ).clamp();
  15533. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  15534. const V = V_Neubelt( { dotNV, dotNL } );
  15535. return sheen.mul( D ).mul( V );
  15536. } );
  15537. // Rect Area Light
  15538. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  15539. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  15540. // code: https://github.com/selfshadow/ltc_code/
  15541. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  15542. const LUT_SIZE = 64.0;
  15543. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  15544. const LUT_BIAS = 0.5 / LUT_SIZE;
  15545. const dotNV = N.dot( V ).saturate();
  15546. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  15547. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  15548. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  15549. return uv;
  15550. } ).setLayout( {
  15551. name: 'LTC_Uv',
  15552. type: 'vec2',
  15553. inputs: [
  15554. { name: 'N', type: 'vec3' },
  15555. { name: 'V', type: 'vec3' },
  15556. { name: 'roughness', type: 'float' }
  15557. ]
  15558. } );
  15559. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  15560. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  15561. // An approximation of the form factor of a horizon-clipped rectangle.
  15562. const l = f.length();
  15563. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  15564. } ).setLayout( {
  15565. name: 'LTC_ClippedSphereFormFactor',
  15566. type: 'float',
  15567. inputs: [
  15568. { name: 'f', type: 'vec3' }
  15569. ]
  15570. } );
  15571. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  15572. const x = v1.dot( v2 );
  15573. const y = x.abs().toVar();
  15574. // rational polynomial approximation to theta / sin( theta ) / 2PI
  15575. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  15576. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  15577. const v = a.div( b );
  15578. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  15579. return v1.cross( v2 ).mul( theta_sintheta );
  15580. } ).setLayout( {
  15581. name: 'LTC_EdgeVectorFormFactor',
  15582. type: 'vec3',
  15583. inputs: [
  15584. { name: 'v1', type: 'vec3' },
  15585. { name: 'v2', type: 'vec3' }
  15586. ]
  15587. } );
  15588. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  15589. // bail if point is on back side of plane of light
  15590. // assumes ccw winding order of light vertices
  15591. const v1 = p1.sub( p0 ).toVar();
  15592. const v2 = p3.sub( p0 ).toVar();
  15593. const lightNormal = v1.cross( v2 );
  15594. const result = vec3().toVar();
  15595. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15596. // construct orthonormal basis around N
  15597. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  15598. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  15599. // compute transform
  15600. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  15601. // transform rect
  15602. // & project rect onto sphere
  15603. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  15604. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  15605. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  15606. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  15607. // calculate vector form factor
  15608. const vectorFormFactor = vec3( 0 ).toVar();
  15609. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15610. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15611. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15612. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15613. // adjust for horizon clipping
  15614. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  15615. } );
  15616. return result;
  15617. } ).setLayout( {
  15618. name: 'LTC_Evaluate',
  15619. type: 'vec3',
  15620. inputs: [
  15621. { name: 'N', type: 'vec3' },
  15622. { name: 'V', type: 'vec3' },
  15623. { name: 'P', type: 'vec3' },
  15624. { name: 'mInv', type: 'mat3' },
  15625. { name: 'p0', type: 'vec3' },
  15626. { name: 'p1', type: 'vec3' },
  15627. { name: 'p2', type: 'vec3' },
  15628. { name: 'p3', type: 'vec3' }
  15629. ]
  15630. } );
  15631. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  15632. // bail if point is on back side of plane of light
  15633. // assumes ccw winding order of light vertices
  15634. const v1 = p1.sub( p0 ).toVar();
  15635. const v2 = p3.sub( p0 ).toVar();
  15636. const lightNormal = v1.cross( v2 );
  15637. const result = vec3().toVar();
  15638. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15639. // transform rect
  15640. // & project rect onto sphere
  15641. const coords0 = p0.sub( P ).normalize().toVar();
  15642. const coords1 = p1.sub( P ).normalize().toVar();
  15643. const coords2 = p2.sub( P ).normalize().toVar();
  15644. const coords3 = p3.sub( P ).normalize().toVar();
  15645. // calculate vector form factor
  15646. const vectorFormFactor = vec3( 0 ).toVar();
  15647. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15648. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15649. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15650. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15651. // adjust for horizon clipping
  15652. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  15653. } );
  15654. return result;
  15655. } ).setLayout( {
  15656. name: 'LTC_Evaluate',
  15657. type: 'vec3',
  15658. inputs: [
  15659. { name: 'P', type: 'vec3' },
  15660. { name: 'p0', type: 'vec3' },
  15661. { name: 'p1', type: 'vec3' },
  15662. { name: 'p2', type: 'vec3' },
  15663. { name: 'p3', type: 'vec3' }
  15664. ]
  15665. } );
  15666. // Mipped Bicubic Texture Filtering by N8
  15667. // https://www.shadertoy.com/view/Dl2SDW
  15668. const bC = 1.0 / 6.0;
  15669. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  15670. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  15671. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  15672. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  15673. const g0 = ( a ) => w0( a ).add( w1( a ) );
  15674. const g1 = ( a ) => w2( a ).add( w3( a ) );
  15675. // h0 and h1 are the two offset functions
  15676. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  15677. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  15678. const bicubic = ( textureNode, texelSize, lod ) => {
  15679. const uv = textureNode.uvNode;
  15680. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  15681. const iuv = floor( uvScaled );
  15682. const fuv = fract( uvScaled );
  15683. const g0x = g0( fuv.x );
  15684. const g1x = g1( fuv.x );
  15685. const h0x = h0( fuv.x );
  15686. const h1x = h1( fuv.x );
  15687. const h0y = h0( fuv.y );
  15688. const h1y = h1( fuv.y );
  15689. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15690. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15691. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15692. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15693. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  15694. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  15695. return a.add( b );
  15696. };
  15697. /**
  15698. * Applies mipped bicubic texture filtering to the given texture node.
  15699. *
  15700. * @tsl
  15701. * @function
  15702. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15703. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  15704. * @return {Node} The filtered texture sample.
  15705. */
  15706. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  15707. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  15708. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  15709. const fLodSizeInv = div( 1.0, fLodSize );
  15710. const cLodSizeInv = div( 1.0, cLodSize );
  15711. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  15712. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  15713. return fract( lodNode ).mix( fSample, cSample );
  15714. } );
  15715. /**
  15716. * Applies mipped bicubic texture filtering to the given texture node.
  15717. *
  15718. * @tsl
  15719. * @function
  15720. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15721. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  15722. * @return {Node} The filtered texture sample.
  15723. */
  15724. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  15725. const lod = strength.mul( maxMipLevel( textureNode ) );
  15726. return textureBicubicLevel( textureNode, lod );
  15727. } );
  15728. //
  15729. // Transmission
  15730. //
  15731. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  15732. // Direction of refracted light.
  15733. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  15734. // Compute rotation-independent scaling of the model matrix.
  15735. const modelScale = vec3(
  15736. length( modelMatrix[ 0 ].xyz ),
  15737. length( modelMatrix[ 1 ].xyz ),
  15738. length( modelMatrix[ 2 ].xyz )
  15739. );
  15740. // The thickness is specified in local space.
  15741. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  15742. } ).setLayout( {
  15743. name: 'getVolumeTransmissionRay',
  15744. type: 'vec3',
  15745. inputs: [
  15746. { name: 'n', type: 'vec3' },
  15747. { name: 'v', type: 'vec3' },
  15748. { name: 'thickness', type: 'float' },
  15749. { name: 'ior', type: 'float' },
  15750. { name: 'modelMatrix', type: 'mat4' }
  15751. ]
  15752. } );
  15753. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  15754. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  15755. // an IOR of 1.5 results in the default amount of microfacet refraction.
  15756. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  15757. } ).setLayout( {
  15758. name: 'applyIorToRoughness',
  15759. type: 'float',
  15760. inputs: [
  15761. { name: 'roughness', type: 'float' },
  15762. { name: 'ior', type: 'float' }
  15763. ]
  15764. } );
  15765. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  15766. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  15767. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  15768. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  15769. const transmissionSample = vTexture.sample( fragCoord );
  15770. //const transmissionSample = viewportMipTexture( fragCoord );
  15771. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  15772. return textureBicubicLevel( transmissionSample, lod );
  15773. } );
  15774. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  15775. If( attenuationDistance.notEqual( 0 ), () => {
  15776. // Compute light attenuation using Beer's law.
  15777. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  15778. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  15779. return transmittance;
  15780. } );
  15781. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  15782. return vec3( 1.0 );
  15783. } ).setLayout( {
  15784. name: 'volumeAttenuation',
  15785. type: 'vec3',
  15786. inputs: [
  15787. { name: 'transmissionDistance', type: 'float' },
  15788. { name: 'attenuationColor', type: 'vec3' },
  15789. { name: 'attenuationDistance', type: 'float' }
  15790. ]
  15791. } );
  15792. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  15793. let transmittedLight, transmittance;
  15794. if ( dispersion ) {
  15795. transmittedLight = vec4().toVar();
  15796. transmittance = vec3().toVar();
  15797. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  15798. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  15799. Loop( { start: 0, end: 3 }, ( { i } ) => {
  15800. const ior = iors.element( i );
  15801. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15802. const refractedRayExit = position.add( transmissionRay );
  15803. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15804. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15805. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15806. refractionCoords.addAssign( 1.0 );
  15807. refractionCoords.divAssign( 2.0 );
  15808. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15809. // Sample framebuffer to get pixel the refracted ray hits.
  15810. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  15811. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  15812. transmittedLight.a.addAssign( transmissionSample.a );
  15813. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  15814. } );
  15815. transmittedLight.a.divAssign( 3.0 );
  15816. } else {
  15817. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15818. const refractedRayExit = position.add( transmissionRay );
  15819. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15820. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15821. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15822. refractionCoords.addAssign( 1.0 );
  15823. refractionCoords.divAssign( 2.0 );
  15824. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15825. // Sample framebuffer to get pixel the refracted ray hits.
  15826. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  15827. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  15828. }
  15829. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  15830. const dotNV = n.dot( v ).clamp();
  15831. // Get the specular component.
  15832. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  15833. dotNV,
  15834. specularColor,
  15835. specularF90,
  15836. roughness
  15837. } ) );
  15838. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  15839. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  15840. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  15841. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  15842. } );
  15843. //
  15844. // Iridescence
  15845. //
  15846. // XYZ to linear-sRGB color space
  15847. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  15848. 3.2404542, -0.969266, 0.0556434,
  15849. -1.5371385, 1.8760108, -0.2040259,
  15850. -0.4985314, 0.0415560, 1.0572252
  15851. );
  15852. // Assume air interface for top
  15853. // Note: We don't handle the case fresnel0 == 1
  15854. const Fresnel0ToIor = ( fresnel0 ) => {
  15855. const sqrtF0 = fresnel0.sqrt();
  15856. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  15857. };
  15858. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  15859. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  15860. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  15861. };
  15862. // Fresnel equations for dielectric/dielectric interfaces.
  15863. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  15864. // Evaluation XYZ sensitivity curves in Fourier space
  15865. const evalSensitivity = ( OPD, shift ) => {
  15866. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  15867. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  15868. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  15869. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  15870. 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() );
  15871. 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() );
  15872. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  15873. const rgb = XYZ_TO_REC709.mul( xyz );
  15874. return rgb;
  15875. };
  15876. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  15877. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  15878. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  15879. // Evaluate the cosTheta on the base layer (Snell law)
  15880. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  15881. // Handle TIR:
  15882. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  15883. If( cosTheta2Sq.lessThan( 0 ), () => {
  15884. return vec3( 1.0 );
  15885. } );
  15886. const cosTheta2 = cosTheta2Sq.sqrt();
  15887. // First interface
  15888. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  15889. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  15890. //const R21 = R12;
  15891. const T121 = R12.oneMinus();
  15892. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  15893. const phi21 = float( Math.PI ).sub( phi12 );
  15894. // Second interface
  15895. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  15896. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  15897. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  15898. const phi23 = vec3(
  15899. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15900. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15901. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  15902. );
  15903. // Phase shift
  15904. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  15905. const phi = vec3( phi21 ).add( phi23 );
  15906. // Compound terms
  15907. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  15908. const r123 = R123.sqrt();
  15909. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  15910. // Reflectance term for m = 0 (DC term amplitude)
  15911. const C0 = R12.add( Rs );
  15912. const I = C0.toVar();
  15913. // Reflectance term for m > 0 (pairs of diracs)
  15914. const Cm = Rs.sub( T121 ).toVar();
  15915. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  15916. Cm.mulAssign( r123 );
  15917. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  15918. I.addAssign( Cm.mul( Sm ) );
  15919. } );
  15920. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  15921. return I.max( vec3( 0.0 ) );
  15922. } ).setLayout( {
  15923. name: 'evalIridescence',
  15924. type: 'vec3',
  15925. inputs: [
  15926. { name: 'outsideIOR', type: 'float' },
  15927. { name: 'eta2', type: 'float' },
  15928. { name: 'cosTheta1', type: 'float' },
  15929. { name: 'thinFilmThickness', type: 'float' },
  15930. { name: 'baseF0', type: 'vec3' }
  15931. ]
  15932. } );
  15933. //
  15934. // Sheen
  15935. //
  15936. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  15937. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  15938. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  15939. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  15940. const dotNV = normal.dot( viewDir ).saturate();
  15941. const r2 = roughness.pow2();
  15942. const a = select(
  15943. roughness.lessThan( 0.25 ),
  15944. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  15945. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  15946. );
  15947. const b = select(
  15948. roughness.lessThan( 0.25 ),
  15949. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  15950. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  15951. );
  15952. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  15953. return DG.mul( 1.0 / Math.PI ).saturate();
  15954. } );
  15955. const clearcoatF0 = vec3( 0.04 );
  15956. const clearcoatF90 = float( 1 );
  15957. /**
  15958. * Represents the lighting model for a PBR material.
  15959. *
  15960. * @augments LightingModel
  15961. */
  15962. class PhysicalLightingModel extends LightingModel {
  15963. /**
  15964. * Constructs a new physical lighting model.
  15965. *
  15966. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15967. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  15968. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  15969. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15970. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  15971. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  15972. */
  15973. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  15974. super();
  15975. /**
  15976. * Whether clearcoat is supported or not.
  15977. *
  15978. * @type {boolean}
  15979. * @default false
  15980. */
  15981. this.clearcoat = clearcoat;
  15982. /**
  15983. * Whether sheen is supported or not.
  15984. *
  15985. * @type {boolean}
  15986. * @default false
  15987. */
  15988. this.sheen = sheen;
  15989. /**
  15990. * Whether iridescence is supported or not.
  15991. *
  15992. * @type {boolean}
  15993. * @default false
  15994. */
  15995. this.iridescence = iridescence;
  15996. /**
  15997. * Whether anisotropy is supported or not.
  15998. *
  15999. * @type {boolean}
  16000. * @default false
  16001. */
  16002. this.anisotropy = anisotropy;
  16003. /**
  16004. * Whether transmission is supported or not.
  16005. *
  16006. * @type {boolean}
  16007. * @default false
  16008. */
  16009. this.transmission = transmission;
  16010. /**
  16011. * Whether dispersion is supported or not.
  16012. *
  16013. * @type {boolean}
  16014. * @default false
  16015. */
  16016. this.dispersion = dispersion;
  16017. /**
  16018. * The clear coat radiance.
  16019. *
  16020. * @type {?Node}
  16021. * @default null
  16022. */
  16023. this.clearcoatRadiance = null;
  16024. /**
  16025. * The clear coat specular direct.
  16026. *
  16027. * @type {?Node}
  16028. * @default null
  16029. */
  16030. this.clearcoatSpecularDirect = null;
  16031. /**
  16032. * The clear coat specular indirect.
  16033. *
  16034. * @type {?Node}
  16035. * @default null
  16036. */
  16037. this.clearcoatSpecularIndirect = null;
  16038. /**
  16039. * The sheen specular direct.
  16040. *
  16041. * @type {?Node}
  16042. * @default null
  16043. */
  16044. this.sheenSpecularDirect = null;
  16045. /**
  16046. * The sheen specular indirect.
  16047. *
  16048. * @type {?Node}
  16049. * @default null
  16050. */
  16051. this.sheenSpecularIndirect = null;
  16052. /**
  16053. * The iridescence Fresnel.
  16054. *
  16055. * @type {?Node}
  16056. * @default null
  16057. */
  16058. this.iridescenceFresnel = null;
  16059. /**
  16060. * The iridescence F0.
  16061. *
  16062. * @type {?Node}
  16063. * @default null
  16064. */
  16065. this.iridescenceF0 = null;
  16066. }
  16067. /**
  16068. * Depending on what features are requested, the method prepares certain node variables
  16069. * which are later used for lighting computations.
  16070. *
  16071. * @param {NodeBuilder} builder - The current node builder.
  16072. */
  16073. start( builder ) {
  16074. if ( this.clearcoat === true ) {
  16075. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  16076. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  16077. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  16078. }
  16079. if ( this.sheen === true ) {
  16080. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  16081. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  16082. }
  16083. if ( this.iridescence === true ) {
  16084. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  16085. this.iridescenceFresnel = evalIridescence( {
  16086. outsideIOR: float( 1.0 ),
  16087. eta2: iridescenceIOR,
  16088. cosTheta1: dotNVi,
  16089. thinFilmThickness: iridescenceThickness,
  16090. baseF0: specularColor
  16091. } );
  16092. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  16093. }
  16094. if ( this.transmission === true ) {
  16095. const position = positionWorld;
  16096. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  16097. const n = normalWorld;
  16098. const context = builder.context;
  16099. context.backdrop = getIBLVolumeRefraction(
  16100. n,
  16101. v,
  16102. roughness,
  16103. diffuseColor,
  16104. specularColor,
  16105. specularF90, // specularF90
  16106. position, // positionWorld
  16107. modelWorldMatrix, // modelMatrix
  16108. cameraViewMatrix, // viewMatrix
  16109. cameraProjectionMatrix, // projMatrix
  16110. ior,
  16111. thickness,
  16112. attenuationColor,
  16113. attenuationDistance,
  16114. this.dispersion ? dispersion : null
  16115. );
  16116. context.backdropAlpha = transmission;
  16117. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  16118. }
  16119. super.start( builder );
  16120. }
  16121. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  16122. // Approximates multi-scattering in order to preserve energy.
  16123. // http://www.jcgt.org/published/0008/01/03/
  16124. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  16125. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16126. const fab = DFGApprox( { roughness, dotNV } );
  16127. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  16128. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16129. const Ess = fab.x.add( fab.y );
  16130. const Ems = Ess.oneMinus();
  16131. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  16132. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  16133. singleScatter.addAssign( FssEss );
  16134. multiScatter.addAssign( Fms.mul( Ems ) );
  16135. }
  16136. /**
  16137. * Implements the direct light.
  16138. *
  16139. * @param {Object} lightData - The light data.
  16140. * @param {NodeBuilder} builder - The current node builder.
  16141. */
  16142. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  16143. const dotNL = normalView.dot( lightDirection ).clamp();
  16144. const irradiance = dotNL.mul( lightColor );
  16145. if ( this.sheen === true ) {
  16146. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  16147. }
  16148. if ( this.clearcoat === true ) {
  16149. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  16150. const ccIrradiance = dotNLcc.mul( lightColor );
  16151. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  16152. }
  16153. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16154. 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 } ) ) );
  16155. }
  16156. /**
  16157. * This method is intended for implementing the direct light term for
  16158. * rect area light nodes.
  16159. *
  16160. * @param {Object} input - The input data.
  16161. * @param {NodeBuilder} builder - The current node builder.
  16162. */
  16163. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  16164. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  16165. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  16166. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  16167. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  16168. const N = normalView;
  16169. const V = positionViewDirection;
  16170. const P = positionView.toVar();
  16171. const uv = LTC_Uv( { N, V, roughness } );
  16172. const t1 = ltc_1.sample( uv ).toVar();
  16173. const t2 = ltc_2.sample( uv ).toVar();
  16174. const mInv = mat3(
  16175. vec3( t1.x, 0, t1.y ),
  16176. vec3( 0, 1, 0 ),
  16177. vec3( t1.z, 0, t1.w )
  16178. ).toVar();
  16179. // LTC Fresnel Approximation by Stephen Hill
  16180. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  16181. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  16182. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  16183. 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 } ) ) );
  16184. }
  16185. /**
  16186. * Implements the indirect lighting.
  16187. *
  16188. * @param {NodeBuilder} builder - The current node builder.
  16189. */
  16190. indirect( builder ) {
  16191. this.indirectDiffuse( builder );
  16192. this.indirectSpecular( builder );
  16193. this.ambientOcclusion( builder );
  16194. }
  16195. /**
  16196. * Implements the indirect diffuse term.
  16197. *
  16198. * @param {NodeBuilder} builder - The current node builder.
  16199. */
  16200. indirectDiffuse( builder ) {
  16201. const { irradiance, reflectedLight } = builder.context;
  16202. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16203. }
  16204. /**
  16205. * Implements the indirect specular term.
  16206. *
  16207. * @param {NodeBuilder} builder - The current node builder.
  16208. */
  16209. indirectSpecular( builder ) {
  16210. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  16211. if ( this.sheen === true ) {
  16212. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  16213. sheen,
  16214. IBLSheenBRDF( {
  16215. normal: normalView,
  16216. viewDir: positionViewDirection,
  16217. roughness: sheenRoughness
  16218. } )
  16219. ) );
  16220. }
  16221. if ( this.clearcoat === true ) {
  16222. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16223. const clearcoatEnv = EnvironmentBRDF( {
  16224. dotNV: dotNVcc,
  16225. specularColor: clearcoatF0,
  16226. specularF90: clearcoatF90,
  16227. roughness: clearcoatRoughness
  16228. } );
  16229. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  16230. }
  16231. // Both indirect specular and indirect diffuse light accumulate here
  16232. const singleScattering = vec3().toVar( 'singleScattering' );
  16233. const multiScattering = vec3().toVar( 'multiScattering' );
  16234. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  16235. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  16236. const totalScattering = singleScattering.add( multiScattering );
  16237. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  16238. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  16239. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  16240. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  16241. }
  16242. /**
  16243. * Implements the ambient occlusion term.
  16244. *
  16245. * @param {NodeBuilder} builder - The current node builder.
  16246. */
  16247. ambientOcclusion( builder ) {
  16248. const { ambientOcclusion, reflectedLight } = builder.context;
  16249. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16250. const aoNV = dotNV.add( ambientOcclusion );
  16251. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  16252. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  16253. if ( this.clearcoat === true ) {
  16254. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  16255. }
  16256. if ( this.sheen === true ) {
  16257. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  16258. }
  16259. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16260. reflectedLight.indirectSpecular.mulAssign( aoNode );
  16261. }
  16262. /**
  16263. * Used for final lighting accumulations depending on the requested features.
  16264. *
  16265. * @param {NodeBuilder} builder - The current node builder.
  16266. */
  16267. finish( { context } ) {
  16268. const { outgoingLight } = context;
  16269. if ( this.clearcoat === true ) {
  16270. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16271. const Fcc = F_Schlick( {
  16272. dotVH: dotNVcc,
  16273. f0: clearcoatF0,
  16274. f90: clearcoatF90
  16275. } );
  16276. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  16277. outgoingLight.assign( clearcoatLight );
  16278. }
  16279. if ( this.sheen === true ) {
  16280. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  16281. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  16282. outgoingLight.assign( sheenLight );
  16283. }
  16284. }
  16285. }
  16286. // These defines must match with PMREMGenerator
  16287. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  16288. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  16289. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  16290. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  16291. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  16292. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  16293. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  16294. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  16295. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  16296. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  16297. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  16298. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  16299. // These shader functions convert between the UV coordinates of a single face of
  16300. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  16301. // sampling a textureCube (not generally normalized ).
  16302. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  16303. const absDirection = vec3( abs( direction ) ).toVar();
  16304. const face = float( -1 ).toVar();
  16305. If( absDirection.x.greaterThan( absDirection.z ), () => {
  16306. If( absDirection.x.greaterThan( absDirection.y ), () => {
  16307. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  16308. } ).Else( () => {
  16309. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16310. } );
  16311. } ).Else( () => {
  16312. If( absDirection.z.greaterThan( absDirection.y ), () => {
  16313. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  16314. } ).Else( () => {
  16315. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16316. } );
  16317. } );
  16318. return face;
  16319. } ).setLayout( {
  16320. name: 'getFace',
  16321. type: 'float',
  16322. inputs: [
  16323. { name: 'direction', type: 'vec3' }
  16324. ]
  16325. } );
  16326. // RH coordinate system; PMREM face-indexing convention
  16327. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  16328. const uv = vec2().toVar();
  16329. If( face.equal( 0.0 ), () => {
  16330. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  16331. } ).ElseIf( face.equal( 1.0 ), () => {
  16332. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  16333. } ).ElseIf( face.equal( 2.0 ), () => {
  16334. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  16335. } ).ElseIf( face.equal( 3.0 ), () => {
  16336. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  16337. } ).ElseIf( face.equal( 4.0 ), () => {
  16338. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  16339. } ).Else( () => {
  16340. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  16341. } );
  16342. return mul( 0.5, uv.add( 1.0 ) );
  16343. } ).setLayout( {
  16344. name: 'getUV',
  16345. type: 'vec2',
  16346. inputs: [
  16347. { name: 'direction', type: 'vec3' },
  16348. { name: 'face', type: 'float' }
  16349. ]
  16350. } );
  16351. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  16352. const mip = float( 0.0 ).toVar();
  16353. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  16354. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  16355. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  16356. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  16357. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  16358. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  16359. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  16360. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  16361. } ).Else( () => {
  16362. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  16363. } );
  16364. return mip;
  16365. } ).setLayout( {
  16366. name: 'roughnessToMip',
  16367. type: 'float',
  16368. inputs: [
  16369. { name: 'roughness', type: 'float' }
  16370. ]
  16371. } );
  16372. // RH coordinate system; PMREM face-indexing convention
  16373. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  16374. const uv = uv_immutable.toVar();
  16375. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  16376. const direction = vec3( uv, 1.0 ).toVar();
  16377. If( face.equal( 0.0 ), () => {
  16378. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  16379. } ).ElseIf( face.equal( 1.0 ), () => {
  16380. direction.assign( direction.xzy );
  16381. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  16382. } ).ElseIf( face.equal( 2.0 ), () => {
  16383. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  16384. } ).ElseIf( face.equal( 3.0 ), () => {
  16385. direction.assign( direction.zyx );
  16386. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  16387. } ).ElseIf( face.equal( 4.0 ), () => {
  16388. direction.assign( direction.xzy );
  16389. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  16390. } ).ElseIf( face.equal( 5.0 ), () => {
  16391. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  16392. } );
  16393. return direction;
  16394. } ).setLayout( {
  16395. name: 'getDirection',
  16396. type: 'vec3',
  16397. inputs: [
  16398. { name: 'uv', type: 'vec2' },
  16399. { name: 'face', type: 'float' }
  16400. ]
  16401. } );
  16402. //
  16403. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16404. const roughness = float( roughness_immutable );
  16405. const sampleDir = vec3( sampleDir_immutable );
  16406. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  16407. const mipF = fract( mip );
  16408. const mipInt = floor( mip );
  16409. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16410. If( mipF.notEqual( 0.0 ), () => {
  16411. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16412. color0.assign( mix( color0, color1, mipF ) );
  16413. } );
  16414. return color0;
  16415. } );
  16416. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16417. const mipInt = float( mipInt_immutable ).toVar();
  16418. const direction = vec3( direction_immutable );
  16419. const face = float( getFace( direction ) ).toVar();
  16420. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  16421. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  16422. const faceSize = float( exp2( mipInt ) ).toVar();
  16423. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  16424. If( face.greaterThan( 2.0 ), () => {
  16425. uv.y.addAssign( faceSize );
  16426. face.subAssign( 3.0 );
  16427. } );
  16428. uv.x.addAssign( face.mul( faceSize ) );
  16429. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  16430. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  16431. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  16432. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  16433. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  16434. } );
  16435. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16436. const cosTheta = cos( theta );
  16437. // Rodrigues' axis-angle rotation
  16438. const sampleDirection = outputDirection.mul( cosTheta )
  16439. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  16440. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  16441. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  16442. } );
  16443. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16444. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  16445. If( axis.equal( vec3( 0.0 ) ), () => {
  16446. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  16447. } );
  16448. axis.assign( normalize( axis ) );
  16449. const gl_FragColor = vec3().toVar();
  16450. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16451. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  16452. If( i.greaterThanEqual( samples ), () => {
  16453. Break();
  16454. } );
  16455. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  16456. 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 } ) ) );
  16457. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16458. } );
  16459. return vec4( gl_FragColor, 1 );
  16460. } );
  16461. const LOD_MIN = 4;
  16462. // The standard deviations (radians) associated with the extra mips. These are
  16463. // chosen to approximate a Trowbridge-Reitz distribution function times the
  16464. // geometric shadowing function. These sigma values squared must match the
  16465. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  16466. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  16467. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  16468. // samples and exit early, but not recompile the shader.
  16469. const MAX_SAMPLES = 20;
  16470. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  16471. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  16472. const _clearColor$2 = /*@__PURE__*/ new Color();
  16473. let _oldTarget = null;
  16474. let _oldActiveCubeFace = 0;
  16475. let _oldActiveMipmapLevel = 0;
  16476. // Golden Ratio
  16477. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  16478. const INV_PHI = 1 / PHI;
  16479. // Vertices of a dodecahedron (except the opposites, which represent the
  16480. // same axis), used as axis directions evenly spread on a sphere.
  16481. const _axisDirections = [
  16482. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  16483. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  16484. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  16485. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  16486. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  16487. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  16488. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  16489. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  16490. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  16491. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  16492. ];
  16493. const _origin = /*@__PURE__*/ new Vector3();
  16494. // maps blur materials to their uniforms dictionary
  16495. const _uniformsMap = new WeakMap();
  16496. // WebGPU Face indices
  16497. const _faceLib = [
  16498. 3, 1, 5,
  16499. 0, 4, 2
  16500. ];
  16501. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  16502. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  16503. /**
  16504. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  16505. * (PMREM) from a cubeMap environment texture. This allows different levels of
  16506. * blur to be quickly accessed based on material roughness. It is packed into a
  16507. * special CubeUV format that allows us to perform custom interpolation so that
  16508. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  16509. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  16510. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  16511. * higher roughness levels. In this way we maintain resolution to smoothly
  16512. * interpolate diffuse lighting while limiting sampling computation.
  16513. *
  16514. * Paper: Fast, Accurate Image-Based Lighting:
  16515. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  16516. */
  16517. class PMREMGenerator {
  16518. /**
  16519. * Constructs a new PMREM generator.
  16520. *
  16521. * @param {Renderer} renderer - The renderer.
  16522. */
  16523. constructor( renderer ) {
  16524. this._renderer = renderer;
  16525. this._pingPongRenderTarget = null;
  16526. this._lodMax = 0;
  16527. this._cubeSize = 0;
  16528. this._lodPlanes = [];
  16529. this._sizeLods = [];
  16530. this._sigmas = [];
  16531. this._lodMeshes = [];
  16532. this._blurMaterial = null;
  16533. this._cubemapMaterial = null;
  16534. this._equirectMaterial = null;
  16535. this._backgroundBox = null;
  16536. }
  16537. get _hasInitialized() {
  16538. return this._renderer.hasInitialized();
  16539. }
  16540. /**
  16541. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16542. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16543. * in radians to be applied to the scene before PMREM generation. Optional near
  16544. * and far planes ensure the scene is rendered in its entirety.
  16545. *
  16546. * @param {Scene} scene - The scene to be captured.
  16547. * @param {number} [sigma=0] - The blur radius in radians.
  16548. * @param {number} [near=0.1] - The near plane distance.
  16549. * @param {number} [far=100] - The far plane distance.
  16550. * @param {Object} [options={}] - The configuration options.
  16551. * @param {number} [options.size=256] - The texture size of the PMREM.
  16552. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  16553. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16554. * @return {RenderTarget} The resulting PMREM.
  16555. * @see {@link PMREMGenerator#fromSceneAsync}
  16556. */
  16557. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16558. const {
  16559. size = 256,
  16560. position = _origin,
  16561. renderTarget = null,
  16562. } = options;
  16563. this._setSize( size );
  16564. if ( this._hasInitialized === false ) {
  16565. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  16566. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16567. options.renderTarget = cubeUVRenderTarget;
  16568. this.fromSceneAsync( scene, sigma, near, far, options );
  16569. return cubeUVRenderTarget;
  16570. }
  16571. _oldTarget = this._renderer.getRenderTarget();
  16572. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16573. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16574. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16575. cubeUVRenderTarget.depthBuffer = true;
  16576. this._init( cubeUVRenderTarget );
  16577. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  16578. if ( sigma > 0 ) {
  16579. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  16580. }
  16581. this._applyPMREM( cubeUVRenderTarget );
  16582. this._cleanup( cubeUVRenderTarget );
  16583. return cubeUVRenderTarget;
  16584. }
  16585. /**
  16586. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16587. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16588. * in radians to be applied to the scene before PMREM generation. Optional near
  16589. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  16590. * is placed at the origin).
  16591. *
  16592. * @param {Scene} scene - The scene to be captured.
  16593. * @param {number} [sigma=0] - The blur radius in radians.
  16594. * @param {number} [near=0.1] - The near plane distance.
  16595. * @param {number} [far=100] - The far plane distance.
  16596. * @param {Object} [options={}] - The configuration options.
  16597. * @param {number} [options.size=256] - The texture size of the PMREM.
  16598. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  16599. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16600. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  16601. * @see {@link PMREMGenerator#fromScene}
  16602. */
  16603. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16604. if ( this._hasInitialized === false ) await this._renderer.init();
  16605. return this.fromScene( scene, sigma, near, far, options );
  16606. }
  16607. /**
  16608. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16609. * or HDR. The ideal input image size is 1k (1024 x 512),
  16610. * as this matches best with the 256 x 256 cubemap output.
  16611. *
  16612. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16613. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16614. * @return {RenderTarget} The resulting PMREM.
  16615. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  16616. */
  16617. fromEquirectangular( equirectangular, renderTarget = null ) {
  16618. if ( this._hasInitialized === false ) {
  16619. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  16620. this._setSizeFromTexture( equirectangular );
  16621. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16622. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  16623. return cubeUVRenderTarget;
  16624. }
  16625. return this._fromTexture( equirectangular, renderTarget );
  16626. }
  16627. /**
  16628. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16629. * or HDR. The ideal input image size is 1k (1024 x 512),
  16630. * as this matches best with the 256 x 256 cubemap output.
  16631. *
  16632. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16633. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16634. * @return {Promise<RenderTarget>} The resulting PMREM.
  16635. * @see {@link PMREMGenerator#fromEquirectangular}
  16636. */
  16637. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  16638. if ( this._hasInitialized === false ) await this._renderer.init();
  16639. return this._fromTexture( equirectangular, renderTarget );
  16640. }
  16641. /**
  16642. * Generates a PMREM from an cubemap texture, which can be either LDR
  16643. * or HDR. The ideal input cube size is 256 x 256,
  16644. * as this matches best with the 256 x 256 cubemap output.
  16645. *
  16646. * @param {Texture} cubemap - The cubemap texture to be converted.
  16647. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16648. * @return {RenderTarget} The resulting PMREM.
  16649. * @see {@link PMREMGenerator#fromCubemapAsync}
  16650. */
  16651. fromCubemap( cubemap, renderTarget = null ) {
  16652. if ( this._hasInitialized === false ) {
  16653. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  16654. this._setSizeFromTexture( cubemap );
  16655. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16656. this.fromCubemapAsync( cubemap, renderTarget );
  16657. return cubeUVRenderTarget;
  16658. }
  16659. return this._fromTexture( cubemap, renderTarget );
  16660. }
  16661. /**
  16662. * Generates a PMREM from an cubemap texture, which can be either LDR
  16663. * or HDR. The ideal input cube size is 256 x 256,
  16664. * with the 256 x 256 cubemap output.
  16665. *
  16666. * @param {Texture} cubemap - The cubemap texture to be converted.
  16667. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16668. * @return {Promise<RenderTarget>} The resulting PMREM.
  16669. * @see {@link PMREMGenerator#fromCubemap}
  16670. */
  16671. async fromCubemapAsync( cubemap, renderTarget = null ) {
  16672. if ( this._hasInitialized === false ) await this._renderer.init();
  16673. return this._fromTexture( cubemap, renderTarget );
  16674. }
  16675. /**
  16676. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  16677. * your texture's network fetch for increased concurrency.
  16678. *
  16679. * @returns {Promise}
  16680. */
  16681. async compileCubemapShader() {
  16682. if ( this._cubemapMaterial === null ) {
  16683. this._cubemapMaterial = _getCubemapMaterial();
  16684. await this._compileMaterial( this._cubemapMaterial );
  16685. }
  16686. }
  16687. /**
  16688. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  16689. * your texture's network fetch for increased concurrency.
  16690. *
  16691. * @returns {Promise}
  16692. */
  16693. async compileEquirectangularShader() {
  16694. if ( this._equirectMaterial === null ) {
  16695. this._equirectMaterial = _getEquirectMaterial();
  16696. await this._compileMaterial( this._equirectMaterial );
  16697. }
  16698. }
  16699. /**
  16700. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  16701. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  16702. * one of them will cause any others to also become unusable.
  16703. */
  16704. dispose() {
  16705. this._dispose();
  16706. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  16707. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  16708. if ( this._backgroundBox !== null ) {
  16709. this._backgroundBox.geometry.dispose();
  16710. this._backgroundBox.material.dispose();
  16711. }
  16712. }
  16713. // private interface
  16714. _setSizeFromTexture( texture ) {
  16715. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  16716. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  16717. } else { // Equirectangular
  16718. this._setSize( texture.image.width / 4 );
  16719. }
  16720. }
  16721. _setSize( cubeSize ) {
  16722. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  16723. this._cubeSize = Math.pow( 2, this._lodMax );
  16724. }
  16725. _dispose() {
  16726. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  16727. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  16728. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  16729. this._lodPlanes[ i ].dispose();
  16730. }
  16731. }
  16732. _cleanup( outputTarget ) {
  16733. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  16734. outputTarget.scissorTest = false;
  16735. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  16736. }
  16737. _fromTexture( texture, renderTarget ) {
  16738. this._setSizeFromTexture( texture );
  16739. _oldTarget = this._renderer.getRenderTarget();
  16740. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16741. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16742. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16743. this._init( cubeUVRenderTarget );
  16744. this._textureToCubeUV( texture, cubeUVRenderTarget );
  16745. this._applyPMREM( cubeUVRenderTarget );
  16746. this._cleanup( cubeUVRenderTarget );
  16747. return cubeUVRenderTarget;
  16748. }
  16749. _allocateTarget() {
  16750. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  16751. const height = 4 * this._cubeSize;
  16752. const cubeUVRenderTarget = _createRenderTarget( width, height );
  16753. return cubeUVRenderTarget;
  16754. }
  16755. _init( renderTarget ) {
  16756. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  16757. if ( this._pingPongRenderTarget !== null ) {
  16758. this._dispose();
  16759. }
  16760. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  16761. const { _lodMax } = this;
  16762. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  16763. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  16764. }
  16765. }
  16766. async _compileMaterial( material ) {
  16767. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  16768. await this._renderer.compile( tmpMesh, _flatCamera );
  16769. }
  16770. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  16771. const cubeCamera = _cubeCamera;
  16772. cubeCamera.near = near;
  16773. cubeCamera.far = far;
  16774. // px, py, pz, nx, ny, nz
  16775. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  16776. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  16777. const renderer = this._renderer;
  16778. const originalAutoClear = renderer.autoClear;
  16779. renderer.getClearColor( _clearColor$2 );
  16780. renderer.autoClear = false;
  16781. let backgroundBox = this._backgroundBox;
  16782. if ( backgroundBox === null ) {
  16783. const backgroundMaterial = new MeshBasicMaterial( {
  16784. name: 'PMREM.Background',
  16785. side: BackSide,
  16786. depthWrite: false,
  16787. depthTest: false
  16788. } );
  16789. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  16790. }
  16791. let useSolidColor = false;
  16792. const background = scene.background;
  16793. if ( background ) {
  16794. if ( background.isColor ) {
  16795. backgroundBox.material.color.copy( background );
  16796. scene.background = null;
  16797. useSolidColor = true;
  16798. }
  16799. } else {
  16800. backgroundBox.material.color.copy( _clearColor$2 );
  16801. useSolidColor = true;
  16802. }
  16803. renderer.setRenderTarget( cubeUVRenderTarget );
  16804. renderer.clear();
  16805. if ( useSolidColor ) {
  16806. renderer.render( backgroundBox, cubeCamera );
  16807. }
  16808. for ( let i = 0; i < 6; i ++ ) {
  16809. const col = i % 3;
  16810. if ( col === 0 ) {
  16811. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16812. cubeCamera.position.set( position.x, position.y, position.z );
  16813. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  16814. } else if ( col === 1 ) {
  16815. cubeCamera.up.set( 0, 0, upSign[ i ] );
  16816. cubeCamera.position.set( position.x, position.y, position.z );
  16817. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  16818. } else {
  16819. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16820. cubeCamera.position.set( position.x, position.y, position.z );
  16821. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  16822. }
  16823. const size = this._cubeSize;
  16824. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  16825. renderer.render( scene, cubeCamera );
  16826. }
  16827. renderer.autoClear = originalAutoClear;
  16828. scene.background = background;
  16829. }
  16830. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  16831. const renderer = this._renderer;
  16832. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  16833. if ( isCubeTexture ) {
  16834. if ( this._cubemapMaterial === null ) {
  16835. this._cubemapMaterial = _getCubemapMaterial( texture );
  16836. }
  16837. } else {
  16838. if ( this._equirectMaterial === null ) {
  16839. this._equirectMaterial = _getEquirectMaterial( texture );
  16840. }
  16841. }
  16842. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  16843. material.fragmentNode.value = texture;
  16844. const mesh = this._lodMeshes[ 0 ];
  16845. mesh.material = material;
  16846. const size = this._cubeSize;
  16847. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  16848. renderer.setRenderTarget( cubeUVRenderTarget );
  16849. renderer.render( mesh, _flatCamera );
  16850. }
  16851. _applyPMREM( cubeUVRenderTarget ) {
  16852. const renderer = this._renderer;
  16853. const autoClear = renderer.autoClear;
  16854. renderer.autoClear = false;
  16855. const n = this._lodPlanes.length;
  16856. for ( let i = 1; i < n; i ++ ) {
  16857. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  16858. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  16859. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  16860. }
  16861. renderer.autoClear = autoClear;
  16862. }
  16863. /**
  16864. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  16865. * vertically and horizontally, but this breaks down on a cube. Here we apply
  16866. * the blur latitudinally (around the poles), and then longitudinally (towards
  16867. * the poles) to approximate the orthogonally-separable blur. It is least
  16868. * accurate at the poles, but still does a decent job.
  16869. *
  16870. * @private
  16871. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  16872. * @param {number} lodIn - The input level-of-detail.
  16873. * @param {number} lodOut - The output level-of-detail.
  16874. * @param {number} sigma - The blur radius in radians.
  16875. * @param {Vector3} [poleAxis] - The pole axis.
  16876. */
  16877. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  16878. const pingPongRenderTarget = this._pingPongRenderTarget;
  16879. this._halfBlur(
  16880. cubeUVRenderTarget,
  16881. pingPongRenderTarget,
  16882. lodIn,
  16883. lodOut,
  16884. sigma,
  16885. 'latitudinal',
  16886. poleAxis );
  16887. this._halfBlur(
  16888. pingPongRenderTarget,
  16889. cubeUVRenderTarget,
  16890. lodOut,
  16891. lodOut,
  16892. sigma,
  16893. 'longitudinal',
  16894. poleAxis );
  16895. }
  16896. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  16897. const renderer = this._renderer;
  16898. const blurMaterial = this._blurMaterial;
  16899. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  16900. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  16901. }
  16902. // Number of standard deviations at which to cut off the discrete approximation.
  16903. const STANDARD_DEVIATIONS = 3;
  16904. const blurMesh = this._lodMeshes[ lodOut ];
  16905. blurMesh.material = blurMaterial;
  16906. const blurUniforms = _uniformsMap.get( blurMaterial );
  16907. const pixels = this._sizeLods[ lodIn ] - 1;
  16908. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  16909. const sigmaPixels = sigmaRadians / radiansPerPixel;
  16910. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  16911. if ( samples > MAX_SAMPLES ) {
  16912. console.warn( `sigmaRadians, ${
  16913. sigmaRadians}, is too large and will clip, as it requested ${
  16914. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  16915. }
  16916. const weights = [];
  16917. let sum = 0;
  16918. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  16919. const x = i / sigmaPixels;
  16920. const weight = Math.exp( - x * x / 2 );
  16921. weights.push( weight );
  16922. if ( i === 0 ) {
  16923. sum += weight;
  16924. } else if ( i < samples ) {
  16925. sum += 2 * weight;
  16926. }
  16927. }
  16928. for ( let i = 0; i < weights.length; i ++ ) {
  16929. weights[ i ] = weights[ i ] / sum;
  16930. }
  16931. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  16932. blurUniforms.envMap.value = targetIn.texture;
  16933. blurUniforms.samples.value = samples;
  16934. blurUniforms.weights.array = weights;
  16935. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  16936. if ( poleAxis ) {
  16937. blurUniforms.poleAxis.value = poleAxis;
  16938. }
  16939. const { _lodMax } = this;
  16940. blurUniforms.dTheta.value = radiansPerPixel;
  16941. blurUniforms.mipInt.value = _lodMax - lodIn;
  16942. const outputSize = this._sizeLods[ lodOut ];
  16943. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  16944. const y = 4 * ( this._cubeSize - outputSize );
  16945. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  16946. renderer.setRenderTarget( targetOut );
  16947. renderer.render( blurMesh, _flatCamera );
  16948. }
  16949. }
  16950. function _createPlanes( lodMax ) {
  16951. const lodPlanes = [];
  16952. const sizeLods = [];
  16953. const sigmas = [];
  16954. const lodMeshes = [];
  16955. let lod = lodMax;
  16956. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  16957. for ( let i = 0; i < totalLods; i ++ ) {
  16958. const sizeLod = Math.pow( 2, lod );
  16959. sizeLods.push( sizeLod );
  16960. let sigma = 1.0 / sizeLod;
  16961. if ( i > lodMax - LOD_MIN ) {
  16962. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  16963. } else if ( i === 0 ) {
  16964. sigma = 0;
  16965. }
  16966. sigmas.push( sigma );
  16967. const texelSize = 1.0 / ( sizeLod - 2 );
  16968. const min = - texelSize;
  16969. const max = 1 + texelSize;
  16970. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  16971. const cubeFaces = 6;
  16972. const vertices = 6;
  16973. const positionSize = 3;
  16974. const uvSize = 2;
  16975. const faceIndexSize = 1;
  16976. const position = new Float32Array( positionSize * vertices * cubeFaces );
  16977. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  16978. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  16979. for ( let face = 0; face < cubeFaces; face ++ ) {
  16980. const x = ( face % 3 ) * 2 / 3 - 1;
  16981. const y = face > 2 ? 0 : -1;
  16982. const coordinates = [
  16983. x, y, 0,
  16984. x + 2 / 3, y, 0,
  16985. x + 2 / 3, y + 1, 0,
  16986. x, y, 0,
  16987. x + 2 / 3, y + 1, 0,
  16988. x, y + 1, 0
  16989. ];
  16990. const faceIdx = _faceLib[ face ];
  16991. position.set( coordinates, positionSize * vertices * faceIdx );
  16992. uv.set( uv1, uvSize * vertices * faceIdx );
  16993. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  16994. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  16995. }
  16996. const planes = new BufferGeometry();
  16997. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  16998. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  16999. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  17000. lodPlanes.push( planes );
  17001. lodMeshes.push( new Mesh( planes, null ) );
  17002. if ( lod > LOD_MIN ) {
  17003. lod --;
  17004. }
  17005. }
  17006. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  17007. }
  17008. function _createRenderTarget( width, height ) {
  17009. const params = {
  17010. magFilter: LinearFilter,
  17011. minFilter: LinearFilter,
  17012. generateMipmaps: false,
  17013. type: HalfFloatType,
  17014. format: RGBAFormat,
  17015. colorSpace: LinearSRGBColorSpace,
  17016. //depthBuffer: false
  17017. };
  17018. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  17019. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  17020. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  17021. cubeUVRenderTarget.texture.isPMREMTexture = true;
  17022. cubeUVRenderTarget.scissorTest = true;
  17023. return cubeUVRenderTarget;
  17024. }
  17025. function _setViewport( target, x, y, width, height ) {
  17026. target.viewport.set( x, y, width, height );
  17027. target.scissor.set( x, y, width, height );
  17028. }
  17029. function _getMaterial( type ) {
  17030. const material = new NodeMaterial();
  17031. material.depthTest = false;
  17032. material.depthWrite = false;
  17033. material.blending = NoBlending;
  17034. material.name = `PMREM_${ type }`;
  17035. return material;
  17036. }
  17037. function _getBlurShader( lodMax, width, height ) {
  17038. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  17039. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  17040. const dTheta = uniform( 0 );
  17041. const n = float( MAX_SAMPLES );
  17042. const latitudinal = uniform( 0 ); // false, bool
  17043. const samples = uniform( 1 ); // int
  17044. const envMap = texture( null );
  17045. const mipInt = uniform( 0 ); // int
  17046. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  17047. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  17048. const CUBEUV_MAX_MIP = float( lodMax );
  17049. const materialUniforms = {
  17050. n,
  17051. latitudinal,
  17052. weights,
  17053. poleAxis,
  17054. outputDirection: _outputDirection,
  17055. dTheta,
  17056. samples,
  17057. envMap,
  17058. mipInt,
  17059. CUBEUV_TEXEL_WIDTH,
  17060. CUBEUV_TEXEL_HEIGHT,
  17061. CUBEUV_MAX_MIP
  17062. };
  17063. const material = _getMaterial( 'blur' );
  17064. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  17065. _uniformsMap.set( material, materialUniforms );
  17066. return material;
  17067. }
  17068. function _getCubemapMaterial( envTexture ) {
  17069. const material = _getMaterial( 'cubemap' );
  17070. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  17071. return material;
  17072. }
  17073. function _getEquirectMaterial( envTexture ) {
  17074. const material = _getMaterial( 'equirect' );
  17075. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  17076. return material;
  17077. }
  17078. const _cache = new WeakMap();
  17079. /**
  17080. * Generates the cubeUV size based on the given image height.
  17081. *
  17082. * @private
  17083. * @param {number} imageHeight - The image height.
  17084. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  17085. */
  17086. function _generateCubeUVSize( imageHeight ) {
  17087. const maxMip = Math.log2( imageHeight ) - 2;
  17088. const texelHeight = 1.0 / imageHeight;
  17089. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  17090. return { texelWidth, texelHeight, maxMip };
  17091. }
  17092. /**
  17093. * Generates a PMREM from the given texture.
  17094. *
  17095. * @private
  17096. * @param {Texture} texture - The texture to create the PMREM for.
  17097. * @param {Renderer} renderer - The renderer.
  17098. * @param {PMREMGenerator} generator - The PMREM generator.
  17099. * @return {?Texture} The PMREM.
  17100. */
  17101. function _getPMREMFromTexture( texture, renderer, generator ) {
  17102. const cache = _getCache( renderer );
  17103. let cacheTexture = cache.get( texture );
  17104. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  17105. if ( pmremVersion !== texture.pmremVersion ) {
  17106. const image = texture.image;
  17107. if ( texture.isCubeTexture ) {
  17108. if ( isCubeMapReady( image ) ) {
  17109. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  17110. } else {
  17111. return null;
  17112. }
  17113. } else {
  17114. if ( isEquirectangularMapReady( image ) ) {
  17115. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  17116. } else {
  17117. return null;
  17118. }
  17119. }
  17120. cacheTexture.pmremVersion = texture.pmremVersion;
  17121. cache.set( texture, cacheTexture );
  17122. }
  17123. return cacheTexture.texture;
  17124. }
  17125. /**
  17126. * Returns a cache that stores generated PMREMs for the respective textures.
  17127. * A cache must be maintained per renderer since PMREMs are render target textures
  17128. * which can't be shared across render contexts.
  17129. *
  17130. * @private
  17131. * @param {Renderer} renderer - The renderer.
  17132. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  17133. */
  17134. function _getCache( renderer ) {
  17135. let rendererCache = _cache.get( renderer );
  17136. if ( rendererCache === undefined ) {
  17137. rendererCache = new WeakMap();
  17138. _cache.set( renderer, rendererCache );
  17139. }
  17140. return rendererCache;
  17141. }
  17142. /**
  17143. * This node represents a PMREM which is a special type of preprocessed
  17144. * environment map intended for PBR materials.
  17145. *
  17146. * ```js
  17147. * const material = new MeshStandardNodeMaterial();
  17148. * material.envNode = pmremTexture( envMap );
  17149. * ```
  17150. *
  17151. * @augments TempNode
  17152. */
  17153. class PMREMNode extends TempNode {
  17154. static get type() {
  17155. return 'PMREMNode';
  17156. }
  17157. /**
  17158. * Constructs a new function overloading node.
  17159. *
  17160. * @param {Texture} value - The input texture.
  17161. * @param {Node<vec2>} [uvNode=null] - The uv node.
  17162. * @param {Node<float>} [levelNode=null] - The level node.
  17163. */
  17164. constructor( value, uvNode = null, levelNode = null ) {
  17165. super( 'vec3' );
  17166. /**
  17167. * Reference to the input texture.
  17168. *
  17169. * @private
  17170. * @type {Texture}
  17171. */
  17172. this._value = value;
  17173. /**
  17174. * Reference to the generated PMREM.
  17175. *
  17176. * @private
  17177. * @type {Texture | null}
  17178. * @default null
  17179. */
  17180. this._pmrem = null;
  17181. /**
  17182. * The uv node.
  17183. *
  17184. * @type {Node<vec2>}
  17185. */
  17186. this.uvNode = uvNode;
  17187. /**
  17188. * The level node.
  17189. *
  17190. * @type {Node<float>}
  17191. */
  17192. this.levelNode = levelNode;
  17193. /**
  17194. * Reference to a PMREM generator.
  17195. *
  17196. * @private
  17197. * @type {?PMREMGenerator}
  17198. * @default null
  17199. */
  17200. this._generator = null;
  17201. const defaultTexture = new Texture();
  17202. defaultTexture.isRenderTargetTexture = true;
  17203. /**
  17204. * The texture node holding the generated PMREM.
  17205. *
  17206. * @private
  17207. * @type {TextureNode}
  17208. */
  17209. this._texture = texture( defaultTexture );
  17210. /**
  17211. * A uniform representing the PMREM's width.
  17212. *
  17213. * @private
  17214. * @type {UniformNode<float>}
  17215. */
  17216. this._width = uniform( 0 );
  17217. /**
  17218. * A uniform representing the PMREM's height.
  17219. *
  17220. * @private
  17221. * @type {UniformNode<float>}
  17222. */
  17223. this._height = uniform( 0 );
  17224. /**
  17225. * A uniform representing the PMREM's max Mip.
  17226. *
  17227. * @private
  17228. * @type {UniformNode<float>}
  17229. */
  17230. this._maxMip = uniform( 0 );
  17231. /**
  17232. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  17233. *
  17234. * @type {string}
  17235. * @default 'render'
  17236. */
  17237. this.updateBeforeType = NodeUpdateType.RENDER;
  17238. }
  17239. set value( value ) {
  17240. this._value = value;
  17241. this._pmrem = null;
  17242. }
  17243. /**
  17244. * The node's texture value.
  17245. *
  17246. * @type {Texture}
  17247. */
  17248. get value() {
  17249. return this._value;
  17250. }
  17251. /**
  17252. * Uses the given PMREM texture to update internal values.
  17253. *
  17254. * @param {Texture} texture - The PMREM texture.
  17255. */
  17256. updateFromTexture( texture ) {
  17257. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  17258. this._texture.value = texture;
  17259. this._width.value = cubeUVSize.texelWidth;
  17260. this._height.value = cubeUVSize.texelHeight;
  17261. this._maxMip.value = cubeUVSize.maxMip;
  17262. }
  17263. updateBefore( frame ) {
  17264. let pmrem = this._pmrem;
  17265. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  17266. const texture = this._value;
  17267. if ( pmremVersion !== texture.pmremVersion ) {
  17268. if ( texture.isPMREMTexture === true ) {
  17269. pmrem = texture;
  17270. } else {
  17271. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  17272. }
  17273. if ( pmrem !== null ) {
  17274. this._pmrem = pmrem;
  17275. this.updateFromTexture( pmrem );
  17276. }
  17277. }
  17278. }
  17279. setup( builder ) {
  17280. if ( this._generator === null ) {
  17281. this._generator = new PMREMGenerator( builder.renderer );
  17282. }
  17283. this.updateBefore( builder );
  17284. //
  17285. let uvNode = this.uvNode;
  17286. if ( uvNode === null && builder.context.getUV ) {
  17287. uvNode = builder.context.getUV( this );
  17288. }
  17289. //
  17290. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  17291. //
  17292. let levelNode = this.levelNode;
  17293. if ( levelNode === null && builder.context.getTextureLevel ) {
  17294. levelNode = builder.context.getTextureLevel( this );
  17295. }
  17296. //
  17297. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  17298. }
  17299. dispose() {
  17300. super.dispose();
  17301. if ( this._generator !== null ) this._generator.dispose();
  17302. }
  17303. }
  17304. /**
  17305. * Returns `true` if the given cube map image has been fully loaded.
  17306. *
  17307. * @private
  17308. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  17309. * @return {boolean} Whether the given cube map is ready or not.
  17310. */
  17311. function isCubeMapReady( image ) {
  17312. if ( image === null || image === undefined ) return false;
  17313. let count = 0;
  17314. const length = 6;
  17315. for ( let i = 0; i < length; i ++ ) {
  17316. if ( image[ i ] !== undefined ) count ++;
  17317. }
  17318. return count === length;
  17319. }
  17320. /**
  17321. * Returns `true` if the given equirectangular image has been fully loaded.
  17322. *
  17323. * @private
  17324. * @param {(Image|Object)} image - The equirectangular image.
  17325. * @return {boolean} Whether the given cube map is ready or not.
  17326. */
  17327. function isEquirectangularMapReady( image ) {
  17328. if ( image === null || image === undefined ) return false;
  17329. return image.height > 0;
  17330. }
  17331. /**
  17332. * TSL function for creating a PMREM node.
  17333. *
  17334. * @tsl
  17335. * @function
  17336. * @param {Texture} value - The input texture.
  17337. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  17338. * @param {?Node<float>} [levelNode=null] - The level node.
  17339. * @returns {PMREMNode}
  17340. */
  17341. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  17342. const _envNodeCache = new WeakMap();
  17343. /**
  17344. * Represents a physical model for Image-based lighting (IBL). The environment
  17345. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  17346. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  17347. *
  17348. * @augments LightingNode
  17349. */
  17350. class EnvironmentNode extends LightingNode {
  17351. static get type() {
  17352. return 'EnvironmentNode';
  17353. }
  17354. /**
  17355. * Constructs a new environment node.
  17356. *
  17357. * @param {Node} [envNode=null] - A node representing the environment.
  17358. */
  17359. constructor( envNode = null ) {
  17360. super();
  17361. /**
  17362. * A node representing the environment.
  17363. *
  17364. * @type {?Node}
  17365. * @default null
  17366. */
  17367. this.envNode = envNode;
  17368. }
  17369. setup( builder ) {
  17370. const { material } = builder;
  17371. let envNode = this.envNode;
  17372. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  17373. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  17374. let cacheEnvNode = _envNodeCache.get( value );
  17375. if ( cacheEnvNode === undefined ) {
  17376. cacheEnvNode = pmremTexture( value );
  17377. _envNodeCache.set( value, cacheEnvNode );
  17378. }
  17379. envNode = cacheEnvNode;
  17380. }
  17381. //
  17382. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  17383. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  17384. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  17385. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  17386. const isolateRadiance = cache( radiance );
  17387. const isolateIrradiance = cache( irradiance );
  17388. //
  17389. builder.context.radiance.addAssign( isolateRadiance );
  17390. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  17391. //
  17392. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  17393. if ( clearcoatRadiance ) {
  17394. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  17395. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  17396. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  17397. }
  17398. }
  17399. }
  17400. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  17401. let reflectVec = null;
  17402. return {
  17403. getUV: () => {
  17404. if ( reflectVec === null ) {
  17405. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  17406. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  17407. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  17408. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  17409. }
  17410. return reflectVec;
  17411. },
  17412. getTextureLevel: () => {
  17413. return roughnessNode;
  17414. }
  17415. };
  17416. };
  17417. const createIrradianceContext = ( normalWorldNode ) => {
  17418. return {
  17419. getUV: () => {
  17420. return normalWorldNode;
  17421. },
  17422. getTextureLevel: () => {
  17423. return float( 1.0 );
  17424. }
  17425. };
  17426. };
  17427. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  17428. /**
  17429. * Node material version of {@link MeshStandardMaterial}.
  17430. *
  17431. * @augments NodeMaterial
  17432. */
  17433. class MeshStandardNodeMaterial extends NodeMaterial {
  17434. static get type() {
  17435. return 'MeshStandardNodeMaterial';
  17436. }
  17437. /**
  17438. * Constructs a new mesh standard node material.
  17439. *
  17440. * @param {Object} [parameters] - The configuration parameter.
  17441. */
  17442. constructor( parameters ) {
  17443. super();
  17444. /**
  17445. * This flag can be used for type testing.
  17446. *
  17447. * @type {boolean}
  17448. * @readonly
  17449. * @default true
  17450. */
  17451. this.isMeshStandardNodeMaterial = true;
  17452. /**
  17453. * Set to `true` because standard materials react on lights.
  17454. *
  17455. * @type {boolean}
  17456. * @default true
  17457. */
  17458. this.lights = true;
  17459. /**
  17460. * The emissive color of standard materials is by default inferred from the `emissive`,
  17461. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  17462. * overwrite the default and define the emissive color with a node instead.
  17463. *
  17464. * If you don't want to overwrite the emissive color but modify the existing
  17465. * value instead, use {@link materialEmissive}.
  17466. *
  17467. * @type {?Node<vec3>}
  17468. * @default null
  17469. */
  17470. this.emissiveNode = null;
  17471. /**
  17472. * The metalness of standard materials is by default inferred from the `metalness`,
  17473. * and `metalnessMap` properties. This node property allows to
  17474. * overwrite the default and define the metalness with a node instead.
  17475. *
  17476. * If you don't want to overwrite the metalness but modify the existing
  17477. * value instead, use {@link materialMetalness}.
  17478. *
  17479. * @type {?Node<float>}
  17480. * @default null
  17481. */
  17482. this.metalnessNode = null;
  17483. /**
  17484. * The roughness of standard materials is by default inferred from the `roughness`,
  17485. * and `roughnessMap` properties. This node property allows to
  17486. * overwrite the default and define the roughness with a node instead.
  17487. *
  17488. * If you don't want to overwrite the roughness but modify the existing
  17489. * value instead, use {@link materialRoughness}.
  17490. *
  17491. * @type {?Node<float>}
  17492. * @default null
  17493. */
  17494. this.roughnessNode = null;
  17495. this.setDefaultValues( _defaultValues$6 );
  17496. this.setValues( parameters );
  17497. }
  17498. /**
  17499. * Overwritten since this type of material uses {@link EnvironmentNode}
  17500. * to implement the PBR (PMREM based) environment mapping. Besides, the
  17501. * method honors `Scene.environment`.
  17502. *
  17503. * @param {NodeBuilder} builder - The current node builder.
  17504. * @return {?EnvironmentNode<vec3>} The environment node.
  17505. */
  17506. setupEnvironment( builder ) {
  17507. let envNode = super.setupEnvironment( builder );
  17508. if ( envNode === null && builder.environmentNode ) {
  17509. envNode = builder.environmentNode;
  17510. }
  17511. return envNode ? new EnvironmentNode( envNode ) : null;
  17512. }
  17513. /**
  17514. * Setups the lighting model.
  17515. *
  17516. * @return {PhysicalLightingModel} The lighting model.
  17517. */
  17518. setupLightingModel( /*builder*/ ) {
  17519. return new PhysicalLightingModel();
  17520. }
  17521. /**
  17522. * Setups the specular related node variables.
  17523. */
  17524. setupSpecular() {
  17525. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  17526. specularColor.assign( specularColorNode );
  17527. specularF90.assign( 1.0 );
  17528. }
  17529. /**
  17530. * Setups the standard specific node variables.
  17531. *
  17532. * @param {NodeBuilder} builder - The current node builder.
  17533. */
  17534. setupVariants() {
  17535. // METALNESS
  17536. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  17537. metalness.assign( metalnessNode );
  17538. // ROUGHNESS
  17539. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  17540. roughnessNode = getRoughness( { roughness: roughnessNode } );
  17541. roughness.assign( roughnessNode );
  17542. // SPECULAR COLOR
  17543. this.setupSpecular();
  17544. // DIFFUSE COLOR
  17545. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  17546. }
  17547. copy( source ) {
  17548. this.emissiveNode = source.emissiveNode;
  17549. this.metalnessNode = source.metalnessNode;
  17550. this.roughnessNode = source.roughnessNode;
  17551. return super.copy( source );
  17552. }
  17553. }
  17554. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  17555. /**
  17556. * Node material version of {@link MeshPhysicalMaterial}.
  17557. *
  17558. * @augments MeshStandardNodeMaterial
  17559. */
  17560. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  17561. static get type() {
  17562. return 'MeshPhysicalNodeMaterial';
  17563. }
  17564. /**
  17565. * Constructs a new mesh physical node material.
  17566. *
  17567. * @param {Object} [parameters] - The configuration parameter.
  17568. */
  17569. constructor( parameters ) {
  17570. super();
  17571. /**
  17572. * This flag can be used for type testing.
  17573. *
  17574. * @type {boolean}
  17575. * @readonly
  17576. * @default true
  17577. */
  17578. this.isMeshPhysicalNodeMaterial = true;
  17579. /**
  17580. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  17581. * and `clearcoatMap` properties. This node property allows to overwrite the default
  17582. * and define the clearcoat with a node instead.
  17583. *
  17584. * If you don't want to overwrite the clearcoat but modify the existing
  17585. * value instead, use {@link materialClearcoat}.
  17586. *
  17587. * @type {?Node<float>}
  17588. * @default null
  17589. */
  17590. this.clearcoatNode = null;
  17591. /**
  17592. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  17593. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  17594. * and define the clearcoat roughness with a node instead.
  17595. *
  17596. * If you don't want to overwrite the clearcoat roughness but modify the existing
  17597. * value instead, use {@link materialClearcoatRoughness}.
  17598. *
  17599. * @type {?Node<float>}
  17600. * @default null
  17601. */
  17602. this.clearcoatRoughnessNode = null;
  17603. /**
  17604. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  17605. * property. This node property allows to overwrite the default
  17606. * and define the clearcoat normal with a node instead.
  17607. *
  17608. * If you don't want to overwrite the clearcoat normal but modify the existing
  17609. * value instead, use {@link materialClearcoatNormal}.
  17610. *
  17611. * @type {?Node<vec3>}
  17612. * @default null
  17613. */
  17614. this.clearcoatNormalNode = null;
  17615. /**
  17616. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  17617. * and `sheenColorMap` properties. This node property allows to overwrite the default
  17618. * and define the sheen with a node instead.
  17619. *
  17620. * If you don't want to overwrite the sheen but modify the existing
  17621. * value instead, use {@link materialSheen}.
  17622. *
  17623. * @type {?Node<vec3>}
  17624. * @default null
  17625. */
  17626. this.sheenNode = null;
  17627. /**
  17628. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  17629. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  17630. * and define the sheen roughness with a node instead.
  17631. *
  17632. * If you don't want to overwrite the sheen roughness but modify the existing
  17633. * value instead, use {@link materialSheenRoughness}.
  17634. *
  17635. * @type {?Node<float>}
  17636. * @default null
  17637. */
  17638. this.sheenRoughnessNode = null;
  17639. /**
  17640. * The iridescence of physical materials is by default inferred from the `iridescence`
  17641. * property. This node property allows to overwrite the default
  17642. * and define the iridescence with a node instead.
  17643. *
  17644. * If you don't want to overwrite the iridescence but modify the existing
  17645. * value instead, use {@link materialIridescence}.
  17646. *
  17647. * @type {?Node<float>}
  17648. * @default null
  17649. */
  17650. this.iridescenceNode = null;
  17651. /**
  17652. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  17653. * property. This node property allows to overwrite the default
  17654. * and define the iridescence IOR with a node instead.
  17655. *
  17656. * If you don't want to overwrite the iridescence IOR but modify the existing
  17657. * value instead, use {@link materialIridescenceIOR}.
  17658. *
  17659. * @type {?Node<float>}
  17660. * @default null
  17661. */
  17662. this.iridescenceIORNode = null;
  17663. /**
  17664. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  17665. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  17666. * and define the iridescence thickness with a node instead.
  17667. *
  17668. * If you don't want to overwrite the iridescence thickness but modify the existing
  17669. * value instead, use {@link materialIridescenceThickness}.
  17670. *
  17671. * @type {?Node<float>}
  17672. * @default null
  17673. */
  17674. this.iridescenceThicknessNode = null;
  17675. /**
  17676. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  17677. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  17678. * and define the specular intensity with a node instead.
  17679. *
  17680. * If you don't want to overwrite the specular intensity but modify the existing
  17681. * value instead, use {@link materialSpecularIntensity}.
  17682. *
  17683. * @type {?Node<float>}
  17684. * @default null
  17685. */
  17686. this.specularIntensityNode = null;
  17687. /**
  17688. * The specular color of physical materials is by default inferred from the `specularColor`
  17689. * and `specularColorMap` properties. This node property allows to overwrite the default
  17690. * and define the specular color with a node instead.
  17691. *
  17692. * If you don't want to overwrite the specular color but modify the existing
  17693. * value instead, use {@link materialSpecularColor}.
  17694. *
  17695. * @type {?Node<vec3>}
  17696. * @default null
  17697. */
  17698. this.specularColorNode = null;
  17699. /**
  17700. * The ior of physical materials is by default inferred from the `ior`
  17701. * property. This node property allows to overwrite the default
  17702. * and define the ior with a node instead.
  17703. *
  17704. * If you don't want to overwrite the ior but modify the existing
  17705. * value instead, use {@link materialIOR}.
  17706. *
  17707. * @type {?Node<float>}
  17708. * @default null
  17709. */
  17710. this.iorNode = null;
  17711. /**
  17712. * The transmission of physical materials is by default inferred from the `transmission` and
  17713. * `transmissionMap` properties. This node property allows to overwrite the default
  17714. * and define the transmission with a node instead.
  17715. *
  17716. * If you don't want to overwrite the transmission but modify the existing
  17717. * value instead, use {@link materialTransmission}.
  17718. *
  17719. * @type {?Node<float>}
  17720. * @default null
  17721. */
  17722. this.transmissionNode = null;
  17723. /**
  17724. * The thickness of physical materials is by default inferred from the `thickness` and
  17725. * `thicknessMap` properties. This node property allows to overwrite the default
  17726. * and define the thickness with a node instead.
  17727. *
  17728. * If you don't want to overwrite the thickness but modify the existing
  17729. * value instead, use {@link materialThickness}.
  17730. *
  17731. * @type {?Node<float>}
  17732. * @default null
  17733. */
  17734. this.thicknessNode = null;
  17735. /**
  17736. * The attenuation distance of physical materials is by default inferred from the
  17737. * `attenuationDistance` property. This node property allows to overwrite the default
  17738. * and define the attenuation distance with a node instead.
  17739. *
  17740. * If you don't want to overwrite the attenuation distance but modify the existing
  17741. * value instead, use {@link materialAttenuationDistance}.
  17742. *
  17743. * @type {?Node<float>}
  17744. * @default null
  17745. */
  17746. this.attenuationDistanceNode = null;
  17747. /**
  17748. * The attenuation color of physical materials is by default inferred from the
  17749. * `attenuationColor` property. This node property allows to overwrite the default
  17750. * and define the attenuation color with a node instead.
  17751. *
  17752. * If you don't want to overwrite the attenuation color but modify the existing
  17753. * value instead, use {@link materialAttenuationColor}.
  17754. *
  17755. * @type {?Node<vec3>}
  17756. * @default null
  17757. */
  17758. this.attenuationColorNode = null;
  17759. /**
  17760. * The dispersion of physical materials is by default inferred from the
  17761. * `dispersion` property. This node property allows to overwrite the default
  17762. * and define the dispersion with a node instead.
  17763. *
  17764. * If you don't want to overwrite the dispersion but modify the existing
  17765. * value instead, use {@link materialDispersion}.
  17766. *
  17767. * @type {?Node<float>}
  17768. * @default null
  17769. */
  17770. this.dispersionNode = null;
  17771. /**
  17772. * The anisotropy of physical materials is by default inferred from the
  17773. * `anisotropy` property. This node property allows to overwrite the default
  17774. * and define the anisotropy with a node instead.
  17775. *
  17776. * If you don't want to overwrite the anisotropy but modify the existing
  17777. * value instead, use {@link materialAnisotropy}.
  17778. *
  17779. * @type {?Node<float>}
  17780. * @default null
  17781. */
  17782. this.anisotropyNode = null;
  17783. this.setDefaultValues( _defaultValues$5 );
  17784. this.setValues( parameters );
  17785. }
  17786. /**
  17787. * Whether the lighting model should use clearcoat or not.
  17788. *
  17789. * @type {boolean}
  17790. * @default true
  17791. */
  17792. get useClearcoat() {
  17793. return this.clearcoat > 0 || this.clearcoatNode !== null;
  17794. }
  17795. /**
  17796. * Whether the lighting model should use iridescence or not.
  17797. *
  17798. * @type {boolean}
  17799. * @default true
  17800. */
  17801. get useIridescence() {
  17802. return this.iridescence > 0 || this.iridescenceNode !== null;
  17803. }
  17804. /**
  17805. * Whether the lighting model should use sheen or not.
  17806. *
  17807. * @type {boolean}
  17808. * @default true
  17809. */
  17810. get useSheen() {
  17811. return this.sheen > 0 || this.sheenNode !== null;
  17812. }
  17813. /**
  17814. * Whether the lighting model should use anisotropy or not.
  17815. *
  17816. * @type {boolean}
  17817. * @default true
  17818. */
  17819. get useAnisotropy() {
  17820. return this.anisotropy > 0 || this.anisotropyNode !== null;
  17821. }
  17822. /**
  17823. * Whether the lighting model should use transmission or not.
  17824. *
  17825. * @type {boolean}
  17826. * @default true
  17827. */
  17828. get useTransmission() {
  17829. return this.transmission > 0 || this.transmissionNode !== null;
  17830. }
  17831. /**
  17832. * Whether the lighting model should use dispersion or not.
  17833. *
  17834. * @type {boolean}
  17835. * @default true
  17836. */
  17837. get useDispersion() {
  17838. return this.dispersion > 0 || this.dispersionNode !== null;
  17839. }
  17840. /**
  17841. * Setups the specular related node variables.
  17842. */
  17843. setupSpecular() {
  17844. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  17845. ior.assign( iorNode );
  17846. 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 ) );
  17847. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  17848. }
  17849. /**
  17850. * Setups the lighting model.
  17851. *
  17852. * @return {PhysicalLightingModel} The lighting model.
  17853. */
  17854. setupLightingModel( /*builder*/ ) {
  17855. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  17856. }
  17857. /**
  17858. * Setups the physical specific node variables.
  17859. *
  17860. * @param {NodeBuilder} builder - The current node builder.
  17861. */
  17862. setupVariants( builder ) {
  17863. super.setupVariants( builder );
  17864. // CLEARCOAT
  17865. if ( this.useClearcoat ) {
  17866. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  17867. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  17868. clearcoat.assign( clearcoatNode );
  17869. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  17870. }
  17871. // SHEEN
  17872. if ( this.useSheen ) {
  17873. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  17874. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  17875. sheen.assign( sheenNode );
  17876. sheenRoughness.assign( sheenRoughnessNode );
  17877. }
  17878. // IRIDESCENCE
  17879. if ( this.useIridescence ) {
  17880. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  17881. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  17882. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  17883. iridescence.assign( iridescenceNode );
  17884. iridescenceIOR.assign( iridescenceIORNode );
  17885. iridescenceThickness.assign( iridescenceThicknessNode );
  17886. }
  17887. // ANISOTROPY
  17888. if ( this.useAnisotropy ) {
  17889. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  17890. anisotropy.assign( anisotropyV.length() );
  17891. If( anisotropy.equal( 0.0 ), () => {
  17892. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  17893. } ).Else( () => {
  17894. anisotropyV.divAssign( vec2( anisotropy ) );
  17895. anisotropy.assign( anisotropy.saturate() );
  17896. } );
  17897. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  17898. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  17899. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  17900. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  17901. }
  17902. // TRANSMISSION
  17903. if ( this.useTransmission ) {
  17904. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  17905. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  17906. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  17907. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  17908. transmission.assign( transmissionNode );
  17909. thickness.assign( thicknessNode );
  17910. attenuationDistance.assign( attenuationDistanceNode );
  17911. attenuationColor.assign( attenuationColorNode );
  17912. if ( this.useDispersion ) {
  17913. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  17914. dispersion.assign( dispersionNode );
  17915. }
  17916. }
  17917. }
  17918. /**
  17919. * Setups the clearcoat normal node.
  17920. *
  17921. * @return {Node<vec3>} The clearcoat normal.
  17922. */
  17923. setupClearcoatNormal() {
  17924. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  17925. }
  17926. setup( builder ) {
  17927. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  17928. super.setup( builder );
  17929. }
  17930. copy( source ) {
  17931. this.clearcoatNode = source.clearcoatNode;
  17932. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  17933. this.clearcoatNormalNode = source.clearcoatNormalNode;
  17934. this.sheenNode = source.sheenNode;
  17935. this.sheenRoughnessNode = source.sheenRoughnessNode;
  17936. this.iridescenceNode = source.iridescenceNode;
  17937. this.iridescenceIORNode = source.iridescenceIORNode;
  17938. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  17939. this.specularIntensityNode = source.specularIntensityNode;
  17940. this.specularColorNode = source.specularColorNode;
  17941. this.transmissionNode = source.transmissionNode;
  17942. this.thicknessNode = source.thicknessNode;
  17943. this.attenuationDistanceNode = source.attenuationDistanceNode;
  17944. this.attenuationColorNode = source.attenuationColorNode;
  17945. this.dispersionNode = source.dispersionNode;
  17946. this.anisotropyNode = source.anisotropyNode;
  17947. return super.copy( source );
  17948. }
  17949. }
  17950. /**
  17951. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  17952. *
  17953. * @augments PhysicalLightingModel
  17954. */
  17955. class SSSLightingModel extends PhysicalLightingModel {
  17956. /**
  17957. * Constructs a new physical lighting model.
  17958. *
  17959. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17960. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17961. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17962. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17963. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17964. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17965. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  17966. */
  17967. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  17968. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  17969. /**
  17970. * Whether the lighting model should use SSS or not.
  17971. *
  17972. * @type {boolean}
  17973. * @default false
  17974. */
  17975. this.useSSS = sss;
  17976. }
  17977. /**
  17978. * Extends the default implementation with a SSS term.
  17979. *
  17980. * 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/}
  17981. *
  17982. * @param {Object} input - The input data.
  17983. * @param {NodeBuilder} builder - The current node builder.
  17984. */
  17985. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17986. if ( this.useSSS === true ) {
  17987. const material = builder.material;
  17988. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  17989. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  17990. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  17991. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  17992. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  17993. }
  17994. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  17995. }
  17996. }
  17997. /**
  17998. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  17999. * that implements a Subsurface scattering (SSS) term.
  18000. *
  18001. * @augments MeshPhysicalNodeMaterial
  18002. */
  18003. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  18004. static get type() {
  18005. return 'MeshSSSNodeMaterial';
  18006. }
  18007. /**
  18008. * Constructs a new mesh SSS node material.
  18009. *
  18010. * @param {Object} [parameters] - The configuration parameter.
  18011. */
  18012. constructor( parameters ) {
  18013. super( parameters );
  18014. /**
  18015. * Represents the thickness color.
  18016. *
  18017. * @type {?Node<vec3>}
  18018. * @default null
  18019. */
  18020. this.thicknessColorNode = null;
  18021. /**
  18022. * Represents the distortion factor.
  18023. *
  18024. * @type {?Node<float>}
  18025. */
  18026. this.thicknessDistortionNode = float( 0.1 );
  18027. /**
  18028. * Represents the thickness ambient factor.
  18029. *
  18030. * @type {?Node<float>}
  18031. */
  18032. this.thicknessAmbientNode = float( 0.0 );
  18033. /**
  18034. * Represents the thickness attenuation.
  18035. *
  18036. * @type {?Node<float>}
  18037. */
  18038. this.thicknessAttenuationNode = float( .1 );
  18039. /**
  18040. * Represents the thickness power.
  18041. *
  18042. * @type {?Node<float>}
  18043. */
  18044. this.thicknessPowerNode = float( 2.0 );
  18045. /**
  18046. * Represents the thickness scale.
  18047. *
  18048. * @type {?Node<float>}
  18049. */
  18050. this.thicknessScaleNode = float( 10.0 );
  18051. }
  18052. /**
  18053. * Whether the lighting model should use SSS or not.
  18054. *
  18055. * @type {boolean}
  18056. * @default true
  18057. */
  18058. get useSSS() {
  18059. return this.thicknessColorNode !== null;
  18060. }
  18061. /**
  18062. * Setups the lighting model.
  18063. *
  18064. * @return {SSSLightingModel} The lighting model.
  18065. */
  18066. setupLightingModel( /*builder*/ ) {
  18067. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  18068. }
  18069. copy( source ) {
  18070. this.thicknessColorNode = source.thicknessColorNode;
  18071. this.thicknessDistortionNode = source.thicknessDistortionNode;
  18072. this.thicknessAmbientNode = source.thicknessAmbientNode;
  18073. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  18074. this.thicknessPowerNode = source.thicknessPowerNode;
  18075. this.thicknessScaleNode = source.thicknessScaleNode;
  18076. return super.copy( source );
  18077. }
  18078. }
  18079. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  18080. // dotNL will be from -1.0 to 1.0
  18081. const dotNL = normal.dot( lightDirection );
  18082. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  18083. if ( builder.material.gradientMap ) {
  18084. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  18085. return vec3( gradientMap.r );
  18086. } else {
  18087. const fw = coord.fwidth().mul( 0.5 );
  18088. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  18089. }
  18090. } );
  18091. /**
  18092. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  18093. *
  18094. * @augments LightingModel
  18095. */
  18096. class ToonLightingModel extends LightingModel {
  18097. /**
  18098. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  18099. * reduced to a small number of discrete shades to create a comic-like, flat look.
  18100. *
  18101. * @param {Object} lightData - The light data.
  18102. * @param {NodeBuilder} builder - The current node builder.
  18103. */
  18104. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18105. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  18106. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  18107. }
  18108. /**
  18109. * Implements the indirect lighting.
  18110. *
  18111. * @param {NodeBuilder} builder - The current node builder.
  18112. */
  18113. indirect( builder ) {
  18114. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  18115. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  18116. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18117. }
  18118. }
  18119. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  18120. /**
  18121. * Node material version of {@link MeshToonMaterial}.
  18122. *
  18123. * @augments NodeMaterial
  18124. */
  18125. class MeshToonNodeMaterial extends NodeMaterial {
  18126. static get type() {
  18127. return 'MeshToonNodeMaterial';
  18128. }
  18129. /**
  18130. * Constructs a new mesh toon node material.
  18131. *
  18132. * @param {Object} [parameters] - The configuration parameter.
  18133. */
  18134. constructor( parameters ) {
  18135. super();
  18136. /**
  18137. * This flag can be used for type testing.
  18138. *
  18139. * @type {boolean}
  18140. * @readonly
  18141. * @default true
  18142. */
  18143. this.isMeshToonNodeMaterial = true;
  18144. /**
  18145. * Set to `true` because toon materials react on lights.
  18146. *
  18147. * @type {boolean}
  18148. * @default true
  18149. */
  18150. this.lights = true;
  18151. this.setDefaultValues( _defaultValues$4 );
  18152. this.setValues( parameters );
  18153. }
  18154. /**
  18155. * Setups the lighting model.
  18156. *
  18157. * @return {ToonLightingModel} The lighting model.
  18158. */
  18159. setupLightingModel( /*builder*/ ) {
  18160. return new ToonLightingModel();
  18161. }
  18162. }
  18163. /**
  18164. * TSL function for creating a matcap uv node.
  18165. *
  18166. * Can be used to compute texture coordinates for projecting a
  18167. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  18168. *
  18169. * @tsl
  18170. * @function
  18171. * @returns {Node<vec2>} The matcap UV coordinates.
  18172. */
  18173. const matcapUV = /*@__PURE__*/ Fn( () => {
  18174. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  18175. const y = positionViewDirection.cross( x );
  18176. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  18177. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  18178. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  18179. /**
  18180. * Node material version of {@link MeshMatcapMaterial}.
  18181. *
  18182. * @augments NodeMaterial
  18183. */
  18184. class MeshMatcapNodeMaterial extends NodeMaterial {
  18185. static get type() {
  18186. return 'MeshMatcapNodeMaterial';
  18187. }
  18188. /**
  18189. * Constructs a new mesh normal node material.
  18190. *
  18191. * @param {Object} [parameters] - The configuration parameter.
  18192. */
  18193. constructor( parameters ) {
  18194. super();
  18195. /**
  18196. * This flag can be used for type testing.
  18197. *
  18198. * @type {boolean}
  18199. * @readonly
  18200. * @default true
  18201. */
  18202. this.isMeshMatcapNodeMaterial = true;
  18203. this.setDefaultValues( _defaultValues$3 );
  18204. this.setValues( parameters );
  18205. }
  18206. /**
  18207. * Setups the matcap specific node variables.
  18208. *
  18209. * @param {NodeBuilder} builder - The current node builder.
  18210. */
  18211. setupVariants( builder ) {
  18212. const uv = matcapUV;
  18213. let matcapColor;
  18214. if ( builder.material.matcap ) {
  18215. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  18216. } else {
  18217. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  18218. }
  18219. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  18220. }
  18221. }
  18222. /**
  18223. * Applies a rotation to the given position node.
  18224. *
  18225. * @augments TempNode
  18226. */
  18227. class RotateNode extends TempNode {
  18228. static get type() {
  18229. return 'RotateNode';
  18230. }
  18231. /**
  18232. * Constructs a new rotate node.
  18233. *
  18234. * @param {Node} positionNode - The position node.
  18235. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18236. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18237. */
  18238. constructor( positionNode, rotationNode ) {
  18239. super();
  18240. /**
  18241. * The position node.
  18242. *
  18243. * @type {Node}
  18244. */
  18245. this.positionNode = positionNode;
  18246. /**
  18247. * Represents the rotation that is applied to the position node.
  18248. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18249. *
  18250. * @type {Node}
  18251. */
  18252. this.rotationNode = rotationNode;
  18253. }
  18254. /**
  18255. * The type of the {@link RotateNode#positionNode} defines the node's type.
  18256. *
  18257. * @param {NodeBuilder} builder - The current node builder.
  18258. * @return {string} The node's type.
  18259. */
  18260. getNodeType( builder ) {
  18261. return this.positionNode.getNodeType( builder );
  18262. }
  18263. setup( builder ) {
  18264. const { rotationNode, positionNode } = this;
  18265. const nodeType = this.getNodeType( builder );
  18266. if ( nodeType === 'vec2' ) {
  18267. const cosAngle = rotationNode.cos();
  18268. const sinAngle = rotationNode.sin();
  18269. const rotationMatrix = mat2(
  18270. cosAngle, sinAngle,
  18271. sinAngle.negate(), cosAngle
  18272. );
  18273. return rotationMatrix.mul( positionNode );
  18274. } else {
  18275. const rotation = rotationNode;
  18276. 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 ) );
  18277. 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 ) );
  18278. 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 ) );
  18279. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  18280. }
  18281. }
  18282. }
  18283. /**
  18284. * TSL function for creating a rotate node.
  18285. *
  18286. * @tsl
  18287. * @function
  18288. * @param {Node} positionNode - The position node.
  18289. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18290. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18291. * @returns {RotateNode}
  18292. */
  18293. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  18294. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  18295. /**
  18296. * Node material version of {@link SpriteMaterial}.
  18297. *
  18298. * @augments NodeMaterial
  18299. */
  18300. class SpriteNodeMaterial extends NodeMaterial {
  18301. static get type() {
  18302. return 'SpriteNodeMaterial';
  18303. }
  18304. /**
  18305. * Constructs a new sprite node material.
  18306. *
  18307. * @param {Object} [parameters] - The configuration parameter.
  18308. */
  18309. constructor( parameters ) {
  18310. super();
  18311. /**
  18312. * This flag can be used for type testing.
  18313. *
  18314. * @type {boolean}
  18315. * @readonly
  18316. * @default true
  18317. */
  18318. this.isSpriteNodeMaterial = true;
  18319. this._useSizeAttenuation = true;
  18320. /**
  18321. * This property makes it possible to define the position of the sprite with a
  18322. * node. That can be useful when the material is used with instanced rendering
  18323. * and node data are defined with an instanced attribute node:
  18324. * ```js
  18325. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  18326. * material.positionNode = instancedBufferAttribute( positionAttribute );
  18327. * ```
  18328. * Another possibility is to compute the instanced data with a compute shader:
  18329. * ```js
  18330. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  18331. * particleMaterial.positionNode = positionBuffer.toAttribute();
  18332. * ```
  18333. *
  18334. * @type {?Node<vec2>}
  18335. * @default null
  18336. */
  18337. this.positionNode = null;
  18338. /**
  18339. * The rotation of sprite materials is by default inferred from the `rotation`,
  18340. * property. This node property allows to overwrite the default and define
  18341. * the rotation with a node instead.
  18342. *
  18343. * If you don't want to overwrite the rotation but modify the existing
  18344. * value instead, use {@link materialRotation}.
  18345. *
  18346. * @type {?Node<float>}
  18347. * @default null
  18348. */
  18349. this.rotationNode = null;
  18350. /**
  18351. * This node property provides an additional way to scale sprites next to
  18352. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  18353. * is multiplied with the scale value of this node in the vertex shader.
  18354. *
  18355. * @type {?Node<vec2>}
  18356. * @default null
  18357. */
  18358. this.scaleNode = null;
  18359. /**
  18360. * In Sprites, the transparent property is enabled by default.
  18361. *
  18362. * @type {boolean}
  18363. * @default true
  18364. */
  18365. this.transparent = true;
  18366. this.setDefaultValues( _defaultValues$2 );
  18367. this.setValues( parameters );
  18368. }
  18369. /**
  18370. * Setups the position node in view space. This method implements
  18371. * the sprite specific vertex shader.
  18372. *
  18373. * @param {NodeBuilder} builder - The current node builder.
  18374. * @return {Node<vec3>} The position in view space.
  18375. */
  18376. setupPositionView( builder ) {
  18377. const { object, camera } = builder;
  18378. const sizeAttenuation = this.sizeAttenuation;
  18379. const { positionNode, rotationNode, scaleNode } = this;
  18380. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  18381. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  18382. if ( scaleNode !== null ) {
  18383. scale = scale.mul( vec2( scaleNode ) );
  18384. }
  18385. if ( sizeAttenuation === false ) {
  18386. if ( camera.isPerspectiveCamera ) {
  18387. scale = scale.mul( mvPosition.z.negate() );
  18388. } else {
  18389. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  18390. scale = scale.mul( orthoScale.mul( 2 ) );
  18391. }
  18392. }
  18393. let alignedPosition = positionGeometry.xy;
  18394. if ( object.center && object.center.isVector2 === true ) {
  18395. const center = reference$1( 'center', 'vec2', object );
  18396. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  18397. }
  18398. alignedPosition = alignedPosition.mul( scale );
  18399. const rotation = float( rotationNode || materialRotation );
  18400. const rotatedPosition = rotate( alignedPosition, rotation );
  18401. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  18402. }
  18403. copy( source ) {
  18404. this.positionNode = source.positionNode;
  18405. this.rotationNode = source.rotationNode;
  18406. this.scaleNode = source.scaleNode;
  18407. return super.copy( source );
  18408. }
  18409. /**
  18410. * Whether to use size attenuation or not.
  18411. *
  18412. * @type {boolean}
  18413. * @default true
  18414. */
  18415. get sizeAttenuation() {
  18416. return this._useSizeAttenuation;
  18417. }
  18418. set sizeAttenuation( value ) {
  18419. if ( this._useSizeAttenuation !== value ) {
  18420. this._useSizeAttenuation = value;
  18421. this.needsUpdate = true;
  18422. }
  18423. }
  18424. }
  18425. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  18426. /**
  18427. * Node material version of {@link PointsMaterial}.
  18428. *
  18429. * @augments SpriteNodeMaterial
  18430. */
  18431. class PointsNodeMaterial extends SpriteNodeMaterial {
  18432. static get type() {
  18433. return 'PointsNodeMaterial';
  18434. }
  18435. /**
  18436. * Constructs a new points node material.
  18437. *
  18438. * @param {Object} [parameters] - The configuration parameter.
  18439. */
  18440. constructor( parameters ) {
  18441. super();
  18442. /**
  18443. * This node property provides an additional way to set the point size.
  18444. *
  18445. * @type {?Node<vec2>}
  18446. * @default null
  18447. */
  18448. this.sizeNode = null;
  18449. /**
  18450. * This flag can be used for type testing.
  18451. *
  18452. * @type {boolean}
  18453. * @readonly
  18454. * @default true
  18455. */
  18456. this.isPointsNodeMaterial = true;
  18457. this.setDefaultValues( _defaultValues$1 );
  18458. this.setValues( parameters );
  18459. }
  18460. setupPositionView() {
  18461. const { positionNode } = this;
  18462. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  18463. }
  18464. setupVertex( builder ) {
  18465. const mvp = super.setupVertex( builder );
  18466. // skip further processing if the material is not a node material
  18467. if ( builder.material.isNodeMaterial !== true ) {
  18468. return mvp;
  18469. }
  18470. // ndc space
  18471. const { rotationNode, scaleNode, sizeNode } = this;
  18472. const alignedPosition = positionGeometry.xy.toVar();
  18473. const aspect = viewport.z.div( viewport.w );
  18474. // rotation
  18475. if ( rotationNode && rotationNode.isNode ) {
  18476. const rotation = float( rotationNode );
  18477. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  18478. }
  18479. // point size
  18480. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  18481. if ( this.sizeAttenuation === true ) {
  18482. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  18483. }
  18484. // scale
  18485. if ( scaleNode && scaleNode.isNode ) {
  18486. pointSize = pointSize.mul( vec2( scaleNode ) );
  18487. }
  18488. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  18489. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  18490. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  18491. // back to clip space
  18492. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  18493. //clipPos.xy += offset;
  18494. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  18495. return mvp;
  18496. }
  18497. /**
  18498. * Whether alpha to coverage should be used or not.
  18499. *
  18500. * @type {boolean}
  18501. * @default true
  18502. */
  18503. get alphaToCoverage() {
  18504. return this._useAlphaToCoverage;
  18505. }
  18506. set alphaToCoverage( value ) {
  18507. if ( this._useAlphaToCoverage !== value ) {
  18508. this._useAlphaToCoverage = value;
  18509. this.needsUpdate = true;
  18510. }
  18511. }
  18512. }
  18513. /**
  18514. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  18515. *
  18516. * @augments LightingModel
  18517. */
  18518. class ShadowMaskModel extends LightingModel {
  18519. /**
  18520. * Constructs a new shadow mask model.
  18521. */
  18522. constructor() {
  18523. super();
  18524. /**
  18525. * The shadow mask node.
  18526. *
  18527. * @type {Node}
  18528. */
  18529. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  18530. }
  18531. /**
  18532. * Only used to save the shadow mask.
  18533. *
  18534. * @param {Object} input - The input data.
  18535. */
  18536. direct( { lightNode } ) {
  18537. if ( lightNode.shadowNode !== null ) {
  18538. this.shadowNode.mulAssign( lightNode.shadowNode );
  18539. }
  18540. }
  18541. /**
  18542. * Uses the shadow mask to produce the final color.
  18543. *
  18544. * @param {NodeBuilder} builder - The current node builder.
  18545. */
  18546. finish( { context } ) {
  18547. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  18548. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  18549. }
  18550. }
  18551. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  18552. /**
  18553. * Node material version of {@link ShadowMaterial}.
  18554. *
  18555. * @augments NodeMaterial
  18556. */
  18557. class ShadowNodeMaterial extends NodeMaterial {
  18558. static get type() {
  18559. return 'ShadowNodeMaterial';
  18560. }
  18561. /**
  18562. * Constructs a new shadow node material.
  18563. *
  18564. * @param {Object} [parameters] - The configuration parameter.
  18565. */
  18566. constructor( parameters ) {
  18567. super();
  18568. /**
  18569. * This flag can be used for type testing.
  18570. *
  18571. * @type {boolean}
  18572. * @readonly
  18573. * @default true
  18574. */
  18575. this.isShadowNodeMaterial = true;
  18576. /**
  18577. * Set to `true` because so it's possible to implement
  18578. * the shadow mask effect.
  18579. *
  18580. * @type {boolean}
  18581. * @default true
  18582. */
  18583. this.lights = true;
  18584. /**
  18585. * Overwritten since shadow materials are transparent
  18586. * by default.
  18587. *
  18588. * @type {boolean}
  18589. * @default true
  18590. */
  18591. this.transparent = true;
  18592. this.setDefaultValues( _defaultValues );
  18593. this.setValues( parameters );
  18594. }
  18595. /**
  18596. * Setups the lighting model.
  18597. *
  18598. * @return {ShadowMaskModel} The lighting model.
  18599. */
  18600. setupLightingModel( /*builder*/ ) {
  18601. return new ShadowMaskModel();
  18602. }
  18603. }
  18604. const scatteringDensity = property( 'vec3' );
  18605. const linearDepthRay = property( 'vec3' );
  18606. const outgoingRayLight = property( 'vec3' );
  18607. /**
  18608. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  18609. * This model calculates the scattering and transmittance of light through a volumetric medium.
  18610. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  18611. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  18612. *
  18613. * @augments LightingModel
  18614. */
  18615. class VolumetricLightingModel extends LightingModel {
  18616. constructor() {
  18617. super();
  18618. }
  18619. start( builder ) {
  18620. const { material, context } = builder;
  18621. const startPos = property( 'vec3' );
  18622. const endPos = property( 'vec3' );
  18623. // This approach dynamically changes the direction of the ray,
  18624. // 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.
  18625. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  18626. startPos.assign( cameraPosition );
  18627. endPos.assign( positionWorld );
  18628. } ).Else( () => {
  18629. startPos.assign( positionWorld );
  18630. endPos.assign( cameraPosition );
  18631. } );
  18632. //
  18633. const viewVector = endPos.sub( startPos );
  18634. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  18635. const stepSize = viewVector.length().div( steps ).toVar();
  18636. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  18637. const distTravelled = float( 0.0 ).toVar();
  18638. const transmittance = vec3( 1 ).toVar();
  18639. if ( material.offsetNode ) {
  18640. // reduce banding
  18641. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  18642. }
  18643. Loop( steps, () => {
  18644. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  18645. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  18646. if ( material.depthNode !== null ) {
  18647. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  18648. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  18649. }
  18650. context.positionWorld = positionRay;
  18651. context.shadowPositionWorld = positionRay;
  18652. context.positionView = positionViewRay;
  18653. scatteringDensity.assign( 0 );
  18654. let scatteringNode;
  18655. if ( material.scatteringNode ) {
  18656. scatteringNode = material.scatteringNode( {
  18657. positionRay
  18658. } );
  18659. }
  18660. super.start( builder );
  18661. if ( scatteringNode ) {
  18662. scatteringDensity.mulAssign( scatteringNode );
  18663. }
  18664. // beer's law
  18665. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  18666. transmittance.mulAssign( falloff );
  18667. // move along the ray
  18668. distTravelled.addAssign( stepSize );
  18669. } );
  18670. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  18671. }
  18672. scatteringLight( lightColor, builder ) {
  18673. const sceneDepthNode = builder.context.sceneDepthNode;
  18674. if ( sceneDepthNode ) {
  18675. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  18676. scatteringDensity.addAssign( lightColor );
  18677. } );
  18678. } else {
  18679. scatteringDensity.addAssign( lightColor );
  18680. }
  18681. }
  18682. direct( { lightNode, lightColor }, builder ) {
  18683. // Ignore lights with infinite distance
  18684. if ( lightNode.light.distance === undefined ) return;
  18685. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  18686. const directLight = lightColor.xyz.toVar();
  18687. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  18688. this.scatteringLight( directLight, builder );
  18689. }
  18690. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  18691. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  18692. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  18693. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  18694. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  18695. const P = builder.context.positionView;
  18696. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  18697. this.scatteringLight( directLight, builder );
  18698. }
  18699. finish( builder ) {
  18700. builder.context.outgoingLight.assign( outgoingRayLight );
  18701. }
  18702. }
  18703. /**
  18704. * Volume node material.
  18705. *
  18706. * @augments NodeMaterial
  18707. */
  18708. class VolumeNodeMaterial extends NodeMaterial {
  18709. static get type() {
  18710. return 'VolumeNodeMaterial';
  18711. }
  18712. /**
  18713. * Constructs a new volume node material.
  18714. *
  18715. * @param {Object} [parameters] - The configuration parameter.
  18716. */
  18717. constructor( parameters ) {
  18718. super();
  18719. /**
  18720. * This flag can be used for type testing.
  18721. *
  18722. * @type {boolean}
  18723. * @readonly
  18724. * @default true
  18725. */
  18726. this.isVolumeNodeMaterial = true;
  18727. /**
  18728. * Number of steps used for raymarching.
  18729. *
  18730. * @type {number}
  18731. * @default 25
  18732. */
  18733. this.steps = 25;
  18734. /**
  18735. * Offsets the distance a ray has been traveled through a volume.
  18736. * Can be used to implement dithering to reduce banding.
  18737. *
  18738. * @type {Node<float>}
  18739. * @default null
  18740. */
  18741. this.offsetNode = null;
  18742. /**
  18743. * Node used for scattering calculations.
  18744. *
  18745. * @type {Function|FunctionNode<vec4>}
  18746. * @default null
  18747. */
  18748. this.scatteringNode = null;
  18749. this.lights = true;
  18750. this.transparent = true;
  18751. this.side = BackSide;
  18752. this.depthTest = false;
  18753. this.depthWrite = false;
  18754. this.setValues( parameters );
  18755. }
  18756. setupLightingModel() {
  18757. return new VolumetricLightingModel();
  18758. }
  18759. }
  18760. /**
  18761. * This module manages the internal animation loop of the renderer.
  18762. *
  18763. * @private
  18764. */
  18765. class Animation {
  18766. /**
  18767. * Constructs a new animation loop management component.
  18768. *
  18769. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18770. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18771. */
  18772. constructor( nodes, info ) {
  18773. /**
  18774. * Renderer component for managing nodes related logic.
  18775. *
  18776. * @type {Nodes}
  18777. */
  18778. this.nodes = nodes;
  18779. /**
  18780. * Renderer component for managing metrics and monitoring data.
  18781. *
  18782. * @type {Info}
  18783. */
  18784. this.info = info;
  18785. /**
  18786. * A reference to the context from `requestAnimationFrame()` can
  18787. * be called (usually `window`).
  18788. *
  18789. * @type {?(Window|XRSession)}
  18790. */
  18791. this._context = typeof self !== 'undefined' ? self : null;
  18792. /**
  18793. * The user-defined animation loop.
  18794. *
  18795. * @type {?Function}
  18796. * @default null
  18797. */
  18798. this._animationLoop = null;
  18799. /**
  18800. * The requestId which is returned from the `requestAnimationFrame()` call.
  18801. * Can be used to cancel the stop the animation loop.
  18802. *
  18803. * @type {?number}
  18804. * @default null
  18805. */
  18806. this._requestId = null;
  18807. }
  18808. /**
  18809. * Starts the internal animation loop.
  18810. */
  18811. start() {
  18812. const update = ( time, xrFrame ) => {
  18813. this._requestId = this._context.requestAnimationFrame( update );
  18814. if ( this.info.autoReset === true ) this.info.reset();
  18815. this.nodes.nodeFrame.update();
  18816. this.info.frame = this.nodes.nodeFrame.frameId;
  18817. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  18818. };
  18819. update();
  18820. }
  18821. /**
  18822. * Stops the internal animation loop.
  18823. */
  18824. stop() {
  18825. this._context.cancelAnimationFrame( this._requestId );
  18826. this._requestId = null;
  18827. }
  18828. /**
  18829. * Returns the user-level animation loop.
  18830. *
  18831. * @return {?Function} The animation loop.
  18832. */
  18833. getAnimationLoop() {
  18834. return this._animationLoop;
  18835. }
  18836. /**
  18837. * Defines the user-level animation loop.
  18838. *
  18839. * @param {?Function} callback - The animation loop.
  18840. */
  18841. setAnimationLoop( callback ) {
  18842. this._animationLoop = callback;
  18843. }
  18844. /**
  18845. * Returns the animation context.
  18846. *
  18847. * @return {Window|XRSession} The animation context.
  18848. */
  18849. getContext() {
  18850. return this._context;
  18851. }
  18852. /**
  18853. * Defines the context in which `requestAnimationFrame()` is executed.
  18854. *
  18855. * @param {Window|XRSession} context - The context to set.
  18856. */
  18857. setContext( context ) {
  18858. this._context = context;
  18859. }
  18860. /**
  18861. * Frees all internal resources and stops the animation loop.
  18862. */
  18863. dispose() {
  18864. this.stop();
  18865. }
  18866. }
  18867. /**
  18868. * Data structure for the renderer. It allows defining values
  18869. * with chained, hierarchical keys. Keys are meant to be
  18870. * objects since the module internally works with Weak Maps
  18871. * for performance reasons.
  18872. *
  18873. * @private
  18874. */
  18875. class ChainMap {
  18876. /**
  18877. * Constructs a new Chain Map.
  18878. */
  18879. constructor() {
  18880. /**
  18881. * The root Weak Map.
  18882. *
  18883. * @type {WeakMap}
  18884. */
  18885. this.weakMap = new WeakMap();
  18886. }
  18887. /**
  18888. * Returns the value for the given array of keys.
  18889. *
  18890. * @param {Array<Object>} keys - List of keys.
  18891. * @return {any} The value. Returns `undefined` if no value was found.
  18892. */
  18893. get( keys ) {
  18894. let map = this.weakMap;
  18895. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18896. map = map.get( keys[ i ] );
  18897. if ( map === undefined ) return undefined;
  18898. }
  18899. return map.get( keys[ keys.length - 1 ] );
  18900. }
  18901. /**
  18902. * Sets the value for the given keys.
  18903. *
  18904. * @param {Array<Object>} keys - List of keys.
  18905. * @param {any} value - The value to set.
  18906. * @return {ChainMap} A reference to this Chain Map.
  18907. */
  18908. set( keys, value ) {
  18909. let map = this.weakMap;
  18910. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18911. const key = keys[ i ];
  18912. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  18913. map = map.get( key );
  18914. }
  18915. map.set( keys[ keys.length - 1 ], value );
  18916. return this;
  18917. }
  18918. /**
  18919. * Deletes a value for the given keys.
  18920. *
  18921. * @param {Array<Object>} keys - The keys.
  18922. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  18923. */
  18924. delete( keys ) {
  18925. let map = this.weakMap;
  18926. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18927. map = map.get( keys[ i ] );
  18928. if ( map === undefined ) return false;
  18929. }
  18930. return map.delete( keys[ keys.length - 1 ] );
  18931. }
  18932. }
  18933. let _id$9 = 0;
  18934. function getKeys( obj ) {
  18935. const keys = Object.keys( obj );
  18936. let proto = Object.getPrototypeOf( obj );
  18937. while ( proto ) {
  18938. const descriptors = Object.getOwnPropertyDescriptors( proto );
  18939. for ( const key in descriptors ) {
  18940. if ( descriptors[ key ] !== undefined ) {
  18941. const descriptor = descriptors[ key ];
  18942. if ( descriptor && typeof descriptor.get === 'function' ) {
  18943. keys.push( key );
  18944. }
  18945. }
  18946. }
  18947. proto = Object.getPrototypeOf( proto );
  18948. }
  18949. return keys;
  18950. }
  18951. /**
  18952. * A render object is the renderer's representation of single entity that gets drawn
  18953. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  18954. * scene since render objects also depend from the used material, the current render context
  18955. * and the current scene's lighting.
  18956. *
  18957. * In general, the basic process of the renderer is:
  18958. *
  18959. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  18960. * - Process the render lists by calling one or more render commands for each render item.
  18961. * - For each render command, request a render object and perform the draw.
  18962. *
  18963. * The module provides an interface to get data required for the draw command like the actual
  18964. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  18965. * creating render objects should only be done when necessary.
  18966. *
  18967. * @private
  18968. */
  18969. class RenderObject {
  18970. /**
  18971. * Constructs a new render object.
  18972. *
  18973. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18974. * @param {Geometries} geometries - Renderer component for managing geometries.
  18975. * @param {Renderer} renderer - The renderer.
  18976. * @param {Object3D} object - The 3D object.
  18977. * @param {Material} material - The 3D object's material.
  18978. * @param {Scene} scene - The scene the 3D object belongs to.
  18979. * @param {Camera} camera - The camera the object should be rendered with.
  18980. * @param {LightsNode} lightsNode - The lights node.
  18981. * @param {RenderContext} renderContext - The render context.
  18982. * @param {ClippingContext} clippingContext - The clipping context.
  18983. */
  18984. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  18985. this.id = _id$9 ++;
  18986. /**
  18987. * Renderer component for managing nodes related logic.
  18988. *
  18989. * @type {Nodes}
  18990. * @private
  18991. */
  18992. this._nodes = nodes;
  18993. /**
  18994. * Renderer component for managing geometries.
  18995. *
  18996. * @type {Geometries}
  18997. * @private
  18998. */
  18999. this._geometries = geometries;
  19000. /**
  19001. * The renderer.
  19002. *
  19003. * @type {Renderer}
  19004. */
  19005. this.renderer = renderer;
  19006. /**
  19007. * The 3D object.
  19008. *
  19009. * @type {Object3D}
  19010. */
  19011. this.object = object;
  19012. /**
  19013. * The 3D object's material.
  19014. *
  19015. * @type {Material}
  19016. */
  19017. this.material = material;
  19018. /**
  19019. * The scene the 3D object belongs to.
  19020. *
  19021. * @type {Scene}
  19022. */
  19023. this.scene = scene;
  19024. /**
  19025. * The camera the 3D object should be rendered with.
  19026. *
  19027. * @type {Camera}
  19028. */
  19029. this.camera = camera;
  19030. /**
  19031. * The lights node.
  19032. *
  19033. * @type {LightsNode}
  19034. */
  19035. this.lightsNode = lightsNode;
  19036. /**
  19037. * The render context.
  19038. *
  19039. * @type {RenderContext}
  19040. */
  19041. this.context = renderContext;
  19042. /**
  19043. * The 3D object's geometry.
  19044. *
  19045. * @type {BufferGeometry}
  19046. */
  19047. this.geometry = object.geometry;
  19048. /**
  19049. * The render object's version.
  19050. *
  19051. * @type {number}
  19052. */
  19053. this.version = material.version;
  19054. /**
  19055. * The draw range of the geometry.
  19056. *
  19057. * @type {?Object}
  19058. * @default null
  19059. */
  19060. this.drawRange = null;
  19061. /**
  19062. * An array holding the buffer attributes
  19063. * of the render object. This entails attribute
  19064. * definitions on geometry and node level.
  19065. *
  19066. * @type {?Array<BufferAttribute>}
  19067. * @default null
  19068. */
  19069. this.attributes = null;
  19070. /**
  19071. * An object holding the version of the
  19072. * attributes. The keys are the attribute names
  19073. * and the values are the attribute versions.
  19074. *
  19075. * @type {?Object<string, number>}
  19076. * @default null
  19077. */
  19078. this.attributesId = null;
  19079. /**
  19080. * A reference to a render pipeline the render
  19081. * object is processed with.
  19082. *
  19083. * @type {RenderPipeline}
  19084. * @default null
  19085. */
  19086. this.pipeline = null;
  19087. /**
  19088. * Only relevant for objects using
  19089. * multiple materials. This represents a group entry
  19090. * from the respective `BufferGeometry`.
  19091. *
  19092. * @type {?{start: number, count: number}}
  19093. * @default null
  19094. */
  19095. this.group = null;
  19096. /**
  19097. * An array holding the vertex buffers which can
  19098. * be buffer attributes but also interleaved buffers.
  19099. *
  19100. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  19101. * @default null
  19102. */
  19103. this.vertexBuffers = null;
  19104. /**
  19105. * The parameters for the draw command.
  19106. *
  19107. * @type {?Object}
  19108. * @default null
  19109. */
  19110. this.drawParams = null;
  19111. /**
  19112. * If this render object is used inside a render bundle,
  19113. * this property points to the respective bundle group.
  19114. *
  19115. * @type {?BundleGroup}
  19116. * @default null
  19117. */
  19118. this.bundle = null;
  19119. /**
  19120. * The clipping context.
  19121. *
  19122. * @type {ClippingContext}
  19123. */
  19124. this.clippingContext = clippingContext;
  19125. /**
  19126. * The clipping context's cache key.
  19127. *
  19128. * @type {string}
  19129. */
  19130. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  19131. /**
  19132. * The initial node cache key.
  19133. *
  19134. * @type {number}
  19135. */
  19136. this.initialNodesCacheKey = this.getDynamicCacheKey();
  19137. /**
  19138. * The initial cache key.
  19139. *
  19140. * @type {number}
  19141. */
  19142. this.initialCacheKey = this.getCacheKey();
  19143. /**
  19144. * The node builder state.
  19145. *
  19146. * @type {?NodeBuilderState}
  19147. * @private
  19148. * @default null
  19149. */
  19150. this._nodeBuilderState = null;
  19151. /**
  19152. * An array of bindings.
  19153. *
  19154. * @type {?Array<BindGroup>}
  19155. * @private
  19156. * @default null
  19157. */
  19158. this._bindings = null;
  19159. /**
  19160. * Reference to the node material observer.
  19161. *
  19162. * @type {?NodeMaterialObserver}
  19163. * @private
  19164. * @default null
  19165. */
  19166. this._monitor = null;
  19167. /**
  19168. * An event listener which is defined by `RenderObjects`. It performs
  19169. * clean up tasks when `dispose()` on this render object.
  19170. *
  19171. * @method
  19172. */
  19173. this.onDispose = null;
  19174. /**
  19175. * This flag can be used for type testing.
  19176. *
  19177. * @type {boolean}
  19178. * @readonly
  19179. * @default true
  19180. */
  19181. this.isRenderObject = true;
  19182. /**
  19183. * An event listener which is executed when `dispose()` is called on
  19184. * the material of this render object.
  19185. *
  19186. * @method
  19187. */
  19188. this.onMaterialDispose = () => {
  19189. this.dispose();
  19190. };
  19191. /**
  19192. * An event listener which is executed when `dispose()` is called on
  19193. * the geometry of this render object.
  19194. *
  19195. * @method
  19196. */
  19197. this.onGeometryDispose = () => {
  19198. // clear geometry cache attributes
  19199. this.attributes = null;
  19200. this.attributesId = null;
  19201. };
  19202. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  19203. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  19204. }
  19205. /**
  19206. * Updates the clipping context.
  19207. *
  19208. * @param {ClippingContext} context - The clipping context to set.
  19209. */
  19210. updateClipping( context ) {
  19211. this.clippingContext = context;
  19212. }
  19213. /**
  19214. * Whether the clipping requires an update or not.
  19215. *
  19216. * @type {boolean}
  19217. * @readonly
  19218. */
  19219. get clippingNeedsUpdate() {
  19220. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  19221. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  19222. return true;
  19223. }
  19224. /**
  19225. * The number of clipping planes defined in context of hardware clipping.
  19226. *
  19227. * @type {number}
  19228. * @readonly
  19229. */
  19230. get hardwareClippingPlanes() {
  19231. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  19232. }
  19233. /**
  19234. * Returns the node builder state of this render object.
  19235. *
  19236. * @return {NodeBuilderState} The node builder state.
  19237. */
  19238. getNodeBuilderState() {
  19239. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  19240. }
  19241. /**
  19242. * Returns the node material observer of this render object.
  19243. *
  19244. * @return {NodeMaterialObserver} The node material observer.
  19245. */
  19246. getMonitor() {
  19247. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  19248. }
  19249. /**
  19250. * Returns an array of bind groups of this render object.
  19251. *
  19252. * @return {Array<BindGroup>} The bindings.
  19253. */
  19254. getBindings() {
  19255. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  19256. }
  19257. /**
  19258. * Returns a binding group by group name of this render object.
  19259. *
  19260. * @param {string} name - The name of the binding group.
  19261. * @return {?BindGroup} The bindings.
  19262. */
  19263. getBindingGroup( name ) {
  19264. for ( const bindingGroup of this.getBindings() ) {
  19265. if ( bindingGroup.name === name ) {
  19266. return bindingGroup;
  19267. }
  19268. }
  19269. }
  19270. /**
  19271. * Returns the index of the render object's geometry.
  19272. *
  19273. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19274. */
  19275. getIndex() {
  19276. return this._geometries.getIndex( this );
  19277. }
  19278. /**
  19279. * Returns the indirect buffer attribute.
  19280. *
  19281. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19282. */
  19283. getIndirect() {
  19284. return this._geometries.getIndirect( this );
  19285. }
  19286. /**
  19287. * Returns an array that acts as a key for identifying the render object in a chain map.
  19288. *
  19289. * @return {Array<Object>} An array with object references.
  19290. */
  19291. getChainArray() {
  19292. return [ this.object, this.material, this.context, this.lightsNode ];
  19293. }
  19294. /**
  19295. * This method is used when the geometry of a 3D object has been exchanged and the
  19296. * respective render object now requires an update.
  19297. *
  19298. * @param {BufferGeometry} geometry - The geometry to set.
  19299. */
  19300. setGeometry( geometry ) {
  19301. this.geometry = geometry;
  19302. this.attributes = null;
  19303. this.attributesId = null;
  19304. }
  19305. /**
  19306. * Returns the buffer attributes of the render object. The returned array holds
  19307. * attribute definitions on geometry and node level.
  19308. *
  19309. * @return {Array<BufferAttribute>} An array with buffer attributes.
  19310. */
  19311. getAttributes() {
  19312. if ( this.attributes !== null ) return this.attributes;
  19313. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  19314. const geometry = this.geometry;
  19315. const attributes = [];
  19316. const vertexBuffers = new Set();
  19317. const attributesId = {};
  19318. for ( const nodeAttribute of nodeAttributes ) {
  19319. let attribute;
  19320. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  19321. // node attribute
  19322. attribute = nodeAttribute.node.attribute;
  19323. } else {
  19324. // geometry attribute
  19325. attribute = geometry.getAttribute( nodeAttribute.name );
  19326. attributesId[ nodeAttribute.name ] = attribute.version;
  19327. }
  19328. if ( attribute === undefined ) continue;
  19329. attributes.push( attribute );
  19330. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  19331. vertexBuffers.add( bufferAttribute );
  19332. }
  19333. this.attributes = attributes;
  19334. this.attributesId = attributesId;
  19335. this.vertexBuffers = Array.from( vertexBuffers.values() );
  19336. return attributes;
  19337. }
  19338. /**
  19339. * Returns the vertex buffers of the render object.
  19340. *
  19341. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  19342. */
  19343. getVertexBuffers() {
  19344. if ( this.vertexBuffers === null ) this.getAttributes();
  19345. return this.vertexBuffers;
  19346. }
  19347. /**
  19348. * Returns the draw parameters for the render object.
  19349. *
  19350. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  19351. */
  19352. getDrawParameters() {
  19353. const { object, material, geometry, group, drawRange } = this;
  19354. const drawParams = this.drawParams || ( this.drawParams = {
  19355. vertexCount: 0,
  19356. firstVertex: 0,
  19357. instanceCount: 0,
  19358. firstInstance: 0
  19359. } );
  19360. const index = this.getIndex();
  19361. const hasIndex = ( index !== null );
  19362. let instanceCount = 1;
  19363. if ( geometry.isInstancedBufferGeometry === true ) {
  19364. instanceCount = geometry.instanceCount;
  19365. } else if ( object.count !== undefined ) {
  19366. instanceCount = Math.max( 0, object.count );
  19367. }
  19368. if ( instanceCount === 0 ) return null;
  19369. drawParams.instanceCount = instanceCount;
  19370. if ( object.isBatchedMesh === true ) return drawParams;
  19371. let rangeFactor = 1;
  19372. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  19373. rangeFactor = 2;
  19374. }
  19375. let firstVertex = drawRange.start * rangeFactor;
  19376. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  19377. if ( group !== null ) {
  19378. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  19379. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  19380. }
  19381. const position = geometry.attributes.position;
  19382. let itemCount = Infinity;
  19383. if ( hasIndex ) {
  19384. itemCount = index.count;
  19385. } else if ( position !== undefined && position !== null ) {
  19386. itemCount = position.count;
  19387. }
  19388. firstVertex = Math.max( firstVertex, 0 );
  19389. lastVertex = Math.min( lastVertex, itemCount );
  19390. const count = lastVertex - firstVertex;
  19391. if ( count < 0 || count === Infinity ) return null;
  19392. drawParams.vertexCount = count;
  19393. drawParams.firstVertex = firstVertex;
  19394. return drawParams;
  19395. }
  19396. /**
  19397. * Returns the render object's geometry cache key.
  19398. *
  19399. * The geometry cache key is part of the material cache key.
  19400. *
  19401. * @return {string} The geometry cache key.
  19402. */
  19403. getGeometryCacheKey() {
  19404. const { geometry } = this;
  19405. let cacheKey = '';
  19406. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  19407. const attribute = geometry.attributes[ name ];
  19408. cacheKey += name + ',';
  19409. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  19410. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  19411. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  19412. if ( attribute.normalized ) cacheKey += 'n,';
  19413. }
  19414. // structural equality isn't sufficient for morph targets since the
  19415. // data are maintained in textures. only if the targets are all equal
  19416. // the texture and thus the instance of `MorphNode` can be shared.
  19417. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  19418. const targets = geometry.morphAttributes[ name ];
  19419. cacheKey += 'morph-' + name + ',';
  19420. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  19421. const attribute = targets[ i ];
  19422. cacheKey += attribute.id + ',';
  19423. }
  19424. }
  19425. if ( geometry.index ) {
  19426. cacheKey += 'index,';
  19427. }
  19428. return cacheKey;
  19429. }
  19430. /**
  19431. * Returns the render object's material cache key.
  19432. *
  19433. * The material cache key is part of the render object cache key.
  19434. *
  19435. * @return {number} The material cache key.
  19436. */
  19437. getMaterialCacheKey() {
  19438. const { object, material } = this;
  19439. let cacheKey = material.customProgramCacheKey();
  19440. for ( const property of getKeys( material ) ) {
  19441. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  19442. const value = material[ property ];
  19443. let valueKey;
  19444. if ( value !== null ) {
  19445. // some material values require a formatting
  19446. const type = typeof value;
  19447. if ( type === 'number' ) {
  19448. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  19449. } else if ( type === 'object' ) {
  19450. valueKey = '{';
  19451. if ( value.isTexture ) {
  19452. valueKey += value.mapping;
  19453. }
  19454. valueKey += '}';
  19455. } else {
  19456. valueKey = String( value );
  19457. }
  19458. } else {
  19459. valueKey = String( value );
  19460. }
  19461. cacheKey += /*property + ':' +*/ valueKey + ',';
  19462. }
  19463. cacheKey += this.clippingContextCacheKey + ',';
  19464. if ( object.geometry ) {
  19465. cacheKey += this.getGeometryCacheKey();
  19466. }
  19467. if ( object.skeleton ) {
  19468. cacheKey += object.skeleton.bones.length + ',';
  19469. }
  19470. if ( object.isBatchedMesh ) {
  19471. cacheKey += object._matricesTexture.uuid + ',';
  19472. if ( object._colorsTexture !== null ) {
  19473. cacheKey += object._colorsTexture.uuid + ',';
  19474. }
  19475. }
  19476. if ( object.count > 1 ) {
  19477. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  19478. cacheKey += object.uuid + ',';
  19479. }
  19480. cacheKey += object.receiveShadow + ',';
  19481. return hashString( cacheKey );
  19482. }
  19483. /**
  19484. * Whether the geometry requires an update or not.
  19485. *
  19486. * @type {boolean}
  19487. * @readonly
  19488. */
  19489. get needsGeometryUpdate() {
  19490. if ( this.geometry.id !== this.object.geometry.id ) return true;
  19491. if ( this.attributes !== null ) {
  19492. const attributesId = this.attributesId;
  19493. for ( const name in attributesId ) {
  19494. const attribute = this.geometry.getAttribute( name );
  19495. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  19496. return true;
  19497. }
  19498. }
  19499. }
  19500. return false;
  19501. }
  19502. /**
  19503. * Whether the render object requires an update or not.
  19504. *
  19505. * Note: There are two distinct places where render objects are checked for an update.
  19506. *
  19507. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  19508. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  19509. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  19510. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  19511. * a need for a refresh due to material, geometry or object related value changes.
  19512. *
  19513. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  19514. * that performs the 'needsUpdate' check.
  19515. *
  19516. * @type {boolean}
  19517. * @readonly
  19518. */
  19519. get needsUpdate() {
  19520. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  19521. }
  19522. /**
  19523. * Returns the dynamic cache key which represents a key that is computed per draw command.
  19524. *
  19525. * @return {number} The cache key.
  19526. */
  19527. getDynamicCacheKey() {
  19528. let cacheKey = 0;
  19529. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  19530. // the renderer is inside a shadow pass.
  19531. if ( this.material.isShadowPassMaterial !== true ) {
  19532. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  19533. }
  19534. if ( this.camera.isArrayCamera ) {
  19535. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  19536. }
  19537. if ( this.object.receiveShadow ) {
  19538. cacheKey = hash$1( cacheKey, 1 );
  19539. }
  19540. return cacheKey;
  19541. }
  19542. /**
  19543. * Returns the render object's cache key.
  19544. *
  19545. * @return {number} The cache key.
  19546. */
  19547. getCacheKey() {
  19548. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  19549. }
  19550. /**
  19551. * Frees internal resources.
  19552. */
  19553. dispose() {
  19554. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  19555. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  19556. this.onDispose();
  19557. }
  19558. }
  19559. const _chainKeys$5 = [];
  19560. /**
  19561. * This module manages the render objects of the renderer.
  19562. *
  19563. * @private
  19564. */
  19565. class RenderObjects {
  19566. /**
  19567. * Constructs a new render object management component.
  19568. *
  19569. * @param {Renderer} renderer - The renderer.
  19570. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19571. * @param {Geometries} geometries - Renderer component for managing geometries.
  19572. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  19573. * @param {Bindings} bindings - Renderer component for managing bindings.
  19574. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19575. */
  19576. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  19577. /**
  19578. * The renderer.
  19579. *
  19580. * @type {Renderer}
  19581. */
  19582. this.renderer = renderer;
  19583. /**
  19584. * Renderer component for managing nodes related logic.
  19585. *
  19586. * @type {Nodes}
  19587. */
  19588. this.nodes = nodes;
  19589. /**
  19590. * Renderer component for managing geometries.
  19591. *
  19592. * @type {Geometries}
  19593. */
  19594. this.geometries = geometries;
  19595. /**
  19596. * Renderer component for managing pipelines.
  19597. *
  19598. * @type {Pipelines}
  19599. */
  19600. this.pipelines = pipelines;
  19601. /**
  19602. * Renderer component for managing bindings.
  19603. *
  19604. * @type {Bindings}
  19605. */
  19606. this.bindings = bindings;
  19607. /**
  19608. * Renderer component for managing metrics and monitoring data.
  19609. *
  19610. * @type {Info}
  19611. */
  19612. this.info = info;
  19613. /**
  19614. * A dictionary that manages render contexts in chain maps
  19615. * for each pass ID.
  19616. *
  19617. * @type {Object<string,ChainMap>}
  19618. */
  19619. this.chainMaps = {};
  19620. }
  19621. /**
  19622. * Returns a render object for the given object and state data.
  19623. *
  19624. * @param {Object3D} object - The 3D object.
  19625. * @param {Material} material - The 3D object's material.
  19626. * @param {Scene} scene - The scene the 3D object belongs to.
  19627. * @param {Camera} camera - The camera the 3D object should be rendered with.
  19628. * @param {LightsNode} lightsNode - The lights node.
  19629. * @param {RenderContext} renderContext - The render context.
  19630. * @param {ClippingContext} clippingContext - The clipping context.
  19631. * @param {string} [passId] - An optional ID for identifying the pass.
  19632. * @return {RenderObject} The render object.
  19633. */
  19634. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19635. const chainMap = this.getChainMap( passId );
  19636. // reuse chainArray
  19637. _chainKeys$5[ 0 ] = object;
  19638. _chainKeys$5[ 1 ] = material;
  19639. _chainKeys$5[ 2 ] = renderContext;
  19640. _chainKeys$5[ 3 ] = lightsNode;
  19641. let renderObject = chainMap.get( _chainKeys$5 );
  19642. if ( renderObject === undefined ) {
  19643. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19644. chainMap.set( _chainKeys$5, renderObject );
  19645. } else {
  19646. renderObject.updateClipping( clippingContext );
  19647. if ( renderObject.needsGeometryUpdate ) {
  19648. renderObject.setGeometry( object.geometry );
  19649. }
  19650. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  19651. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  19652. renderObject.dispose();
  19653. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19654. } else {
  19655. renderObject.version = material.version;
  19656. }
  19657. }
  19658. }
  19659. _chainKeys$5.length = 0;
  19660. return renderObject;
  19661. }
  19662. /**
  19663. * Returns a chain map for the given pass ID.
  19664. *
  19665. * @param {string} [passId='default'] - The pass ID.
  19666. * @return {ChainMap} The chain map.
  19667. */
  19668. getChainMap( passId = 'default' ) {
  19669. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  19670. }
  19671. /**
  19672. * Frees internal resources.
  19673. */
  19674. dispose() {
  19675. this.chainMaps = {};
  19676. }
  19677. /**
  19678. * Factory method for creating render objects with the given list of parameters.
  19679. *
  19680. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19681. * @param {Geometries} geometries - Renderer component for managing geometries.
  19682. * @param {Renderer} renderer - The renderer.
  19683. * @param {Object3D} object - The 3D object.
  19684. * @param {Material} material - The object's material.
  19685. * @param {Scene} scene - The scene the 3D object belongs to.
  19686. * @param {Camera} camera - The camera the object should be rendered with.
  19687. * @param {LightsNode} lightsNode - The lights node.
  19688. * @param {RenderContext} renderContext - The render context.
  19689. * @param {ClippingContext} clippingContext - The clipping context.
  19690. * @param {string} [passId] - An optional ID for identifying the pass.
  19691. * @return {RenderObject} The render object.
  19692. */
  19693. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19694. const chainMap = this.getChainMap( passId );
  19695. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  19696. renderObject.onDispose = () => {
  19697. this.pipelines.delete( renderObject );
  19698. this.bindings.delete( renderObject );
  19699. this.nodes.delete( renderObject );
  19700. chainMap.delete( renderObject.getChainArray() );
  19701. };
  19702. return renderObject;
  19703. }
  19704. }
  19705. /**
  19706. * Data structure for the renderer. It is intended to manage
  19707. * data of objects in dictionaries.
  19708. *
  19709. * @private
  19710. */
  19711. class DataMap {
  19712. /**
  19713. * Constructs a new data map.
  19714. */
  19715. constructor() {
  19716. /**
  19717. * `DataMap` internally uses a weak map
  19718. * to manage its data.
  19719. *
  19720. * @type {WeakMap}
  19721. */
  19722. this.data = new WeakMap();
  19723. }
  19724. /**
  19725. * Returns the dictionary for the given object.
  19726. *
  19727. * @param {Object} object - The object.
  19728. * @return {Object} The dictionary.
  19729. */
  19730. get( object ) {
  19731. let map = this.data.get( object );
  19732. if ( map === undefined ) {
  19733. map = {};
  19734. this.data.set( object, map );
  19735. }
  19736. return map;
  19737. }
  19738. /**
  19739. * Deletes the dictionary for the given object.
  19740. *
  19741. * @param {Object} object - The object.
  19742. * @return {?Object} The deleted dictionary.
  19743. */
  19744. delete( object ) {
  19745. let map = null;
  19746. if ( this.data.has( object ) ) {
  19747. map = this.data.get( object );
  19748. this.data.delete( object );
  19749. }
  19750. return map;
  19751. }
  19752. /**
  19753. * Returns `true` if the given object has a dictionary defined.
  19754. *
  19755. * @param {Object} object - The object to test.
  19756. * @return {boolean} Whether a dictionary is defined or not.
  19757. */
  19758. has( object ) {
  19759. return this.data.has( object );
  19760. }
  19761. /**
  19762. * Frees internal resources.
  19763. */
  19764. dispose() {
  19765. this.data = new WeakMap();
  19766. }
  19767. }
  19768. const AttributeType = {
  19769. VERTEX: 1,
  19770. INDEX: 2,
  19771. STORAGE: 3,
  19772. INDIRECT: 4
  19773. };
  19774. // size of a chunk in bytes (STD140 layout)
  19775. const GPU_CHUNK_BYTES = 16;
  19776. // @TODO: Move to src/constants.js
  19777. const BlendColorFactor = 211;
  19778. const OneMinusBlendColorFactor = 212;
  19779. /**
  19780. * This renderer module manages geometry attributes.
  19781. *
  19782. * @private
  19783. * @augments DataMap
  19784. */
  19785. class Attributes extends DataMap {
  19786. /**
  19787. * Constructs a new attribute management component.
  19788. *
  19789. * @param {Backend} backend - The renderer's backend.
  19790. */
  19791. constructor( backend ) {
  19792. super();
  19793. /**
  19794. * The renderer's backend.
  19795. *
  19796. * @type {Backend}
  19797. */
  19798. this.backend = backend;
  19799. }
  19800. /**
  19801. * Deletes the data for the given attribute.
  19802. *
  19803. * @param {BufferAttribute} attribute - The attribute.
  19804. * @return {Object|null} The deleted attribute data.
  19805. */
  19806. delete( attribute ) {
  19807. const attributeData = super.delete( attribute );
  19808. if ( attributeData !== null ) {
  19809. this.backend.destroyAttribute( attribute );
  19810. }
  19811. return attributeData;
  19812. }
  19813. /**
  19814. * Updates the given attribute. This method creates attribute buffers
  19815. * for new attributes and updates data for existing ones.
  19816. *
  19817. * @param {BufferAttribute} attribute - The attribute to update.
  19818. * @param {number} type - The attribute type.
  19819. */
  19820. update( attribute, type ) {
  19821. const data = this.get( attribute );
  19822. if ( data.version === undefined ) {
  19823. if ( type === AttributeType.VERTEX ) {
  19824. this.backend.createAttribute( attribute );
  19825. } else if ( type === AttributeType.INDEX ) {
  19826. this.backend.createIndexAttribute( attribute );
  19827. } else if ( type === AttributeType.STORAGE ) {
  19828. this.backend.createStorageAttribute( attribute );
  19829. } else if ( type === AttributeType.INDIRECT ) {
  19830. this.backend.createIndirectStorageAttribute( attribute );
  19831. }
  19832. data.version = this._getBufferAttribute( attribute ).version;
  19833. } else {
  19834. const bufferAttribute = this._getBufferAttribute( attribute );
  19835. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  19836. this.backend.updateAttribute( attribute );
  19837. data.version = bufferAttribute.version;
  19838. }
  19839. }
  19840. }
  19841. /**
  19842. * Utility method for handling interleaved buffer attributes correctly.
  19843. * To process them, their `InterleavedBuffer` is returned.
  19844. *
  19845. * @param {BufferAttribute} attribute - The attribute.
  19846. * @return {BufferAttribute|InterleavedBuffer}
  19847. */
  19848. _getBufferAttribute( attribute ) {
  19849. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  19850. return attribute;
  19851. }
  19852. }
  19853. /**
  19854. * Returns the wireframe version for the given geometry.
  19855. *
  19856. * @private
  19857. * @function
  19858. * @param {BufferGeometry} geometry - The geometry.
  19859. * @return {number} The version.
  19860. */
  19861. function getWireframeVersion( geometry ) {
  19862. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  19863. }
  19864. /**
  19865. * Returns a wireframe index attribute for the given geometry.
  19866. *
  19867. * @private
  19868. * @function
  19869. * @param {BufferGeometry} geometry - The geometry.
  19870. * @return {BufferAttribute} The wireframe index attribute.
  19871. */
  19872. function getWireframeIndex( geometry ) {
  19873. const indices = [];
  19874. const geometryIndex = geometry.index;
  19875. const geometryPosition = geometry.attributes.position;
  19876. if ( geometryIndex !== null ) {
  19877. const array = geometryIndex.array;
  19878. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  19879. const a = array[ i + 0 ];
  19880. const b = array[ i + 1 ];
  19881. const c = array[ i + 2 ];
  19882. indices.push( a, b, b, c, c, a );
  19883. }
  19884. } else {
  19885. const array = geometryPosition.array;
  19886. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  19887. const a = i + 0;
  19888. const b = i + 1;
  19889. const c = i + 2;
  19890. indices.push( a, b, b, c, c, a );
  19891. }
  19892. }
  19893. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  19894. attribute.version = getWireframeVersion( geometry );
  19895. return attribute;
  19896. }
  19897. /**
  19898. * This renderer module manages geometries.
  19899. *
  19900. * @private
  19901. * @augments DataMap
  19902. */
  19903. class Geometries extends DataMap {
  19904. /**
  19905. * Constructs a new geometry management component.
  19906. *
  19907. * @param {Attributes} attributes - Renderer component for managing attributes.
  19908. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19909. */
  19910. constructor( attributes, info ) {
  19911. super();
  19912. /**
  19913. * Renderer component for managing attributes.
  19914. *
  19915. * @type {Attributes}
  19916. */
  19917. this.attributes = attributes;
  19918. /**
  19919. * Renderer component for managing metrics and monitoring data.
  19920. *
  19921. * @type {Info}
  19922. */
  19923. this.info = info;
  19924. /**
  19925. * Weak Map for managing attributes for wireframe rendering.
  19926. *
  19927. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  19928. */
  19929. this.wireframes = new WeakMap();
  19930. /**
  19931. * This Weak Map is used to make sure buffer attributes are
  19932. * updated only once per render call.
  19933. *
  19934. * @type {WeakMap<BufferAttribute,number>}
  19935. */
  19936. this.attributeCall = new WeakMap();
  19937. }
  19938. /**
  19939. * Returns `true` if the given render object has an initialized geometry.
  19940. *
  19941. * @param {RenderObject} renderObject - The render object.
  19942. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  19943. */
  19944. has( renderObject ) {
  19945. const geometry = renderObject.geometry;
  19946. return super.has( geometry ) && this.get( geometry ).initialized === true;
  19947. }
  19948. /**
  19949. * Prepares the geometry of the given render object for rendering.
  19950. *
  19951. * @param {RenderObject} renderObject - The render object.
  19952. */
  19953. updateForRender( renderObject ) {
  19954. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  19955. this.updateAttributes( renderObject );
  19956. }
  19957. /**
  19958. * Initializes the geometry of the given render object.
  19959. *
  19960. * @param {RenderObject} renderObject - The render object.
  19961. */
  19962. initGeometry( renderObject ) {
  19963. const geometry = renderObject.geometry;
  19964. const geometryData = this.get( geometry );
  19965. geometryData.initialized = true;
  19966. this.info.memory.geometries ++;
  19967. const onDispose = () => {
  19968. this.info.memory.geometries --;
  19969. const index = geometry.index;
  19970. const geometryAttributes = renderObject.getAttributes();
  19971. if ( index !== null ) {
  19972. this.attributes.delete( index );
  19973. }
  19974. for ( const geometryAttribute of geometryAttributes ) {
  19975. this.attributes.delete( geometryAttribute );
  19976. }
  19977. const wireframeAttribute = this.wireframes.get( geometry );
  19978. if ( wireframeAttribute !== undefined ) {
  19979. this.attributes.delete( wireframeAttribute );
  19980. }
  19981. geometry.removeEventListener( 'dispose', onDispose );
  19982. };
  19983. geometry.addEventListener( 'dispose', onDispose );
  19984. }
  19985. /**
  19986. * Updates the geometry attributes of the given render object.
  19987. *
  19988. * @param {RenderObject} renderObject - The render object.
  19989. */
  19990. updateAttributes( renderObject ) {
  19991. // attributes
  19992. const attributes = renderObject.getAttributes();
  19993. for ( const attribute of attributes ) {
  19994. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  19995. this.updateAttribute( attribute, AttributeType.STORAGE );
  19996. } else {
  19997. this.updateAttribute( attribute, AttributeType.VERTEX );
  19998. }
  19999. }
  20000. // indexes
  20001. const index = this.getIndex( renderObject );
  20002. if ( index !== null ) {
  20003. this.updateAttribute( index, AttributeType.INDEX );
  20004. }
  20005. // indirect
  20006. const indirect = renderObject.geometry.indirect;
  20007. if ( indirect !== null ) {
  20008. this.updateAttribute( indirect, AttributeType.INDIRECT );
  20009. }
  20010. }
  20011. /**
  20012. * Updates the given attribute.
  20013. *
  20014. * @param {BufferAttribute} attribute - The attribute to update.
  20015. * @param {number} type - The attribute type.
  20016. */
  20017. updateAttribute( attribute, type ) {
  20018. const callId = this.info.render.calls;
  20019. if ( ! attribute.isInterleavedBufferAttribute ) {
  20020. if ( this.attributeCall.get( attribute ) !== callId ) {
  20021. this.attributes.update( attribute, type );
  20022. this.attributeCall.set( attribute, callId );
  20023. }
  20024. } else {
  20025. if ( this.attributeCall.get( attribute ) === undefined ) {
  20026. this.attributes.update( attribute, type );
  20027. this.attributeCall.set( attribute, callId );
  20028. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  20029. this.attributes.update( attribute, type );
  20030. this.attributeCall.set( attribute.data, callId );
  20031. this.attributeCall.set( attribute, callId );
  20032. }
  20033. }
  20034. }
  20035. /**
  20036. * Returns the indirect buffer attribute of the given render object.
  20037. *
  20038. * @param {RenderObject} renderObject - The render object.
  20039. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20040. */
  20041. getIndirect( renderObject ) {
  20042. return renderObject.geometry.indirect;
  20043. }
  20044. /**
  20045. * Returns the index of the given render object's geometry. This is implemented
  20046. * in a method to return a wireframe index if necessary.
  20047. *
  20048. * @param {RenderObject} renderObject - The render object.
  20049. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20050. */
  20051. getIndex( renderObject ) {
  20052. const { geometry, material } = renderObject;
  20053. let index = geometry.index;
  20054. if ( material.wireframe === true ) {
  20055. const wireframes = this.wireframes;
  20056. let wireframeAttribute = wireframes.get( geometry );
  20057. if ( wireframeAttribute === undefined ) {
  20058. wireframeAttribute = getWireframeIndex( geometry );
  20059. wireframes.set( geometry, wireframeAttribute );
  20060. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  20061. this.attributes.delete( wireframeAttribute );
  20062. wireframeAttribute = getWireframeIndex( geometry );
  20063. wireframes.set( geometry, wireframeAttribute );
  20064. }
  20065. index = wireframeAttribute;
  20066. }
  20067. return index;
  20068. }
  20069. }
  20070. /**
  20071. * This renderer module provides a series of statistical information
  20072. * about the GPU memory and the rendering process. Useful for debugging
  20073. * and monitoring.
  20074. */
  20075. class Info {
  20076. /**
  20077. * Constructs a new info component.
  20078. */
  20079. constructor() {
  20080. /**
  20081. * Whether frame related metrics should automatically
  20082. * be resetted or not. This property should be set to `false`
  20083. * by apps which manage their own animation loop. They must
  20084. * then call `renderer.info.reset()` once per frame manually.
  20085. *
  20086. * @type {boolean}
  20087. * @default true
  20088. */
  20089. this.autoReset = true;
  20090. /**
  20091. * The current frame ID. This ID is managed
  20092. * by `NodeFrame`.
  20093. *
  20094. * @type {number}
  20095. * @readonly
  20096. * @default 0
  20097. */
  20098. this.frame = 0;
  20099. /**
  20100. * The number of render calls since the
  20101. * app has been started.
  20102. *
  20103. * @type {number}
  20104. * @readonly
  20105. * @default 0
  20106. */
  20107. this.calls = 0;
  20108. /**
  20109. * Render related metrics.
  20110. *
  20111. * @type {Object}
  20112. * @readonly
  20113. * @property {number} calls - The number of render calls since the app has been started.
  20114. * @property {number} frameCalls - The number of render calls of the current frame.
  20115. * @property {number} drawCalls - The number of draw calls of the current frame.
  20116. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  20117. * @property {number} points - The number of rendered point primitives of the current frame.
  20118. * @property {number} lines - The number of rendered line primitives of the current frame.
  20119. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  20120. */
  20121. this.render = {
  20122. calls: 0,
  20123. frameCalls: 0,
  20124. drawCalls: 0,
  20125. triangles: 0,
  20126. points: 0,
  20127. lines: 0,
  20128. timestamp: 0,
  20129. };
  20130. /**
  20131. * Compute related metrics.
  20132. *
  20133. * @type {Object}
  20134. * @readonly
  20135. * @property {number} calls - The number of compute calls since the app has been started.
  20136. * @property {number} frameCalls - The number of compute calls of the current frame.
  20137. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  20138. */
  20139. this.compute = {
  20140. calls: 0,
  20141. frameCalls: 0,
  20142. timestamp: 0
  20143. };
  20144. /**
  20145. * Memory related metrics.
  20146. *
  20147. * @type {Object}
  20148. * @readonly
  20149. * @property {number} geometries - The number of active geometries.
  20150. * @property {number} frameCalls - The number of active textures.
  20151. */
  20152. this.memory = {
  20153. geometries: 0,
  20154. textures: 0
  20155. };
  20156. }
  20157. /**
  20158. * This method should be executed per draw call and updates the corresponding metrics.
  20159. *
  20160. * @param {Object3D} object - The 3D object that is going to be rendered.
  20161. * @param {number} count - The vertex or index count.
  20162. * @param {number} instanceCount - The instance count.
  20163. */
  20164. update( object, count, instanceCount ) {
  20165. this.render.drawCalls ++;
  20166. if ( object.isMesh || object.isSprite ) {
  20167. this.render.triangles += instanceCount * ( count / 3 );
  20168. } else if ( object.isPoints ) {
  20169. this.render.points += instanceCount * count;
  20170. } else if ( object.isLineSegments ) {
  20171. this.render.lines += instanceCount * ( count / 2 );
  20172. } else if ( object.isLine ) {
  20173. this.render.lines += instanceCount * ( count - 1 );
  20174. } else {
  20175. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  20176. }
  20177. }
  20178. /**
  20179. * Resets frame related metrics.
  20180. */
  20181. reset() {
  20182. this.render.drawCalls = 0;
  20183. this.render.frameCalls = 0;
  20184. this.compute.frameCalls = 0;
  20185. this.render.triangles = 0;
  20186. this.render.points = 0;
  20187. this.render.lines = 0;
  20188. }
  20189. /**
  20190. * Performs a complete reset of the object.
  20191. */
  20192. dispose() {
  20193. this.reset();
  20194. this.calls = 0;
  20195. this.render.calls = 0;
  20196. this.compute.calls = 0;
  20197. this.render.timestamp = 0;
  20198. this.compute.timestamp = 0;
  20199. this.memory.geometries = 0;
  20200. this.memory.textures = 0;
  20201. }
  20202. }
  20203. /**
  20204. * Abstract class for representing pipelines.
  20205. *
  20206. * @private
  20207. * @abstract
  20208. */
  20209. class Pipeline {
  20210. /**
  20211. * Constructs a new pipeline.
  20212. *
  20213. * @param {string} cacheKey - The pipeline's cache key.
  20214. */
  20215. constructor( cacheKey ) {
  20216. /**
  20217. * The pipeline's cache key.
  20218. *
  20219. * @type {string}
  20220. */
  20221. this.cacheKey = cacheKey;
  20222. /**
  20223. * How often the pipeline is currently in use.
  20224. *
  20225. * @type {number}
  20226. * @default 0
  20227. */
  20228. this.usedTimes = 0;
  20229. }
  20230. }
  20231. /**
  20232. * Class for representing render pipelines.
  20233. *
  20234. * @private
  20235. * @augments Pipeline
  20236. */
  20237. class RenderPipeline extends Pipeline {
  20238. /**
  20239. * Constructs a new render pipeline.
  20240. *
  20241. * @param {string} cacheKey - The pipeline's cache key.
  20242. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  20243. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  20244. */
  20245. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  20246. super( cacheKey );
  20247. /**
  20248. * The pipeline's vertex shader.
  20249. *
  20250. * @type {ProgrammableStage}
  20251. */
  20252. this.vertexProgram = vertexProgram;
  20253. /**
  20254. * The pipeline's fragment shader.
  20255. *
  20256. * @type {ProgrammableStage}
  20257. */
  20258. this.fragmentProgram = fragmentProgram;
  20259. }
  20260. }
  20261. /**
  20262. * Class for representing compute pipelines.
  20263. *
  20264. * @private
  20265. * @augments Pipeline
  20266. */
  20267. class ComputePipeline extends Pipeline {
  20268. /**
  20269. * Constructs a new render pipeline.
  20270. *
  20271. * @param {string} cacheKey - The pipeline's cache key.
  20272. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  20273. */
  20274. constructor( cacheKey, computeProgram ) {
  20275. super( cacheKey );
  20276. /**
  20277. * The pipeline's compute shader.
  20278. *
  20279. * @type {ProgrammableStage}
  20280. */
  20281. this.computeProgram = computeProgram;
  20282. /**
  20283. * This flag can be used for type testing.
  20284. *
  20285. * @type {boolean}
  20286. * @readonly
  20287. * @default true
  20288. */
  20289. this.isComputePipeline = true;
  20290. }
  20291. }
  20292. let _id$8 = 0;
  20293. /**
  20294. * Class for representing programmable stages which are vertex,
  20295. * fragment or compute shaders. Unlike fixed-function states (like blending),
  20296. * they represent the programmable part of a pipeline.
  20297. *
  20298. * @private
  20299. */
  20300. class ProgrammableStage {
  20301. /**
  20302. * Constructs a new programmable stage.
  20303. *
  20304. * @param {string} code - The shader code.
  20305. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  20306. * @param {string} name - The name of the shader.
  20307. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20308. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20309. */
  20310. constructor( code, stage, name, transforms = null, attributes = null ) {
  20311. /**
  20312. * The id of the programmable stage.
  20313. *
  20314. * @type {number}
  20315. */
  20316. this.id = _id$8 ++;
  20317. /**
  20318. * The shader code.
  20319. *
  20320. * @type {string}
  20321. */
  20322. this.code = code;
  20323. /**
  20324. * The type of stage.
  20325. *
  20326. * @type {string}
  20327. */
  20328. this.stage = stage;
  20329. /**
  20330. * The name of the stage.
  20331. * This is used for debugging purposes.
  20332. *
  20333. * @type {string}
  20334. */
  20335. this.name = name;
  20336. /**
  20337. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20338. *
  20339. * @type {?Array<Object>}
  20340. */
  20341. this.transforms = transforms;
  20342. /**
  20343. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20344. *
  20345. * @type {?Array<Object>}
  20346. */
  20347. this.attributes = attributes;
  20348. /**
  20349. * How often the programmable stage is currently in use.
  20350. *
  20351. * @type {number}
  20352. * @default 0
  20353. */
  20354. this.usedTimes = 0;
  20355. }
  20356. }
  20357. /**
  20358. * This renderer module manages the pipelines of the renderer.
  20359. *
  20360. * @private
  20361. * @augments DataMap
  20362. */
  20363. class Pipelines extends DataMap {
  20364. /**
  20365. * Constructs a new pipeline management component.
  20366. *
  20367. * @param {Backend} backend - The renderer's backend.
  20368. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20369. */
  20370. constructor( backend, nodes ) {
  20371. super();
  20372. /**
  20373. * The renderer's backend.
  20374. *
  20375. * @type {Backend}
  20376. */
  20377. this.backend = backend;
  20378. /**
  20379. * Renderer component for managing nodes related logic.
  20380. *
  20381. * @type {Nodes}
  20382. */
  20383. this.nodes = nodes;
  20384. /**
  20385. * A references to the bindings management component.
  20386. * This reference will be set inside the `Bindings`
  20387. * constructor.
  20388. *
  20389. * @type {?Bindings}
  20390. * @default null
  20391. */
  20392. this.bindings = null;
  20393. /**
  20394. * Internal cache for maintaining pipelines.
  20395. * The key of the map is a cache key, the value the pipeline.
  20396. *
  20397. * @type {Map<string,Pipeline>}
  20398. */
  20399. this.caches = new Map();
  20400. /**
  20401. * This dictionary maintains for each shader stage type (vertex,
  20402. * fragment and compute) the programmable stage objects which
  20403. * represent the actual shader code.
  20404. *
  20405. * @type {Object<string,Map>}
  20406. */
  20407. this.programs = {
  20408. vertex: new Map(),
  20409. fragment: new Map(),
  20410. compute: new Map()
  20411. };
  20412. }
  20413. /**
  20414. * Returns a compute pipeline for the given compute node.
  20415. *
  20416. * @param {Node} computeNode - The compute node.
  20417. * @param {Array<BindGroup>} bindings - The bindings.
  20418. * @return {ComputePipeline} The compute pipeline.
  20419. */
  20420. getForCompute( computeNode, bindings ) {
  20421. const { backend } = this;
  20422. const data = this.get( computeNode );
  20423. if ( this._needsComputeUpdate( computeNode ) ) {
  20424. const previousPipeline = data.pipeline;
  20425. if ( previousPipeline ) {
  20426. previousPipeline.usedTimes --;
  20427. previousPipeline.computeProgram.usedTimes --;
  20428. }
  20429. // get shader
  20430. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  20431. // programmable stage
  20432. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  20433. if ( stageCompute === undefined ) {
  20434. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  20435. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  20436. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  20437. backend.createProgram( stageCompute );
  20438. }
  20439. // determine compute pipeline
  20440. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  20441. let pipeline = this.caches.get( cacheKey );
  20442. if ( pipeline === undefined ) {
  20443. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20444. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  20445. }
  20446. // keep track of all used times
  20447. pipeline.usedTimes ++;
  20448. stageCompute.usedTimes ++;
  20449. //
  20450. data.version = computeNode.version;
  20451. data.pipeline = pipeline;
  20452. }
  20453. return data.pipeline;
  20454. }
  20455. /**
  20456. * Returns a render pipeline for the given render object.
  20457. *
  20458. * @param {RenderObject} renderObject - The render object.
  20459. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20460. * @return {RenderPipeline} The render pipeline.
  20461. */
  20462. getForRender( renderObject, promises = null ) {
  20463. const { backend } = this;
  20464. const data = this.get( renderObject );
  20465. if ( this._needsRenderUpdate( renderObject ) ) {
  20466. const previousPipeline = data.pipeline;
  20467. if ( previousPipeline ) {
  20468. previousPipeline.usedTimes --;
  20469. previousPipeline.vertexProgram.usedTimes --;
  20470. previousPipeline.fragmentProgram.usedTimes --;
  20471. }
  20472. // get shader
  20473. const nodeBuilderState = renderObject.getNodeBuilderState();
  20474. const name = renderObject.material ? renderObject.material.name : '';
  20475. // programmable stages
  20476. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  20477. if ( stageVertex === undefined ) {
  20478. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  20479. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  20480. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  20481. backend.createProgram( stageVertex );
  20482. }
  20483. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  20484. if ( stageFragment === undefined ) {
  20485. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  20486. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  20487. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  20488. backend.createProgram( stageFragment );
  20489. }
  20490. // determine render pipeline
  20491. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20492. let pipeline = this.caches.get( cacheKey );
  20493. if ( pipeline === undefined ) {
  20494. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20495. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  20496. } else {
  20497. renderObject.pipeline = pipeline;
  20498. }
  20499. // keep track of all used times
  20500. pipeline.usedTimes ++;
  20501. stageVertex.usedTimes ++;
  20502. stageFragment.usedTimes ++;
  20503. //
  20504. data.pipeline = pipeline;
  20505. }
  20506. return data.pipeline;
  20507. }
  20508. /**
  20509. * Deletes the pipeline for the given render object.
  20510. *
  20511. * @param {RenderObject} object - The render object.
  20512. * @return {?Object} The deleted dictionary.
  20513. */
  20514. delete( object ) {
  20515. const pipeline = this.get( object ).pipeline;
  20516. if ( pipeline ) {
  20517. // pipeline
  20518. pipeline.usedTimes --;
  20519. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  20520. // programs
  20521. if ( pipeline.isComputePipeline ) {
  20522. pipeline.computeProgram.usedTimes --;
  20523. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  20524. } else {
  20525. pipeline.fragmentProgram.usedTimes --;
  20526. pipeline.vertexProgram.usedTimes --;
  20527. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  20528. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  20529. }
  20530. }
  20531. return super.delete( object );
  20532. }
  20533. /**
  20534. * Frees internal resources.
  20535. */
  20536. dispose() {
  20537. super.dispose();
  20538. this.caches = new Map();
  20539. this.programs = {
  20540. vertex: new Map(),
  20541. fragment: new Map(),
  20542. compute: new Map()
  20543. };
  20544. }
  20545. /**
  20546. * Updates the pipeline for the given render object.
  20547. *
  20548. * @param {RenderObject} renderObject - The render object.
  20549. */
  20550. updateForRender( renderObject ) {
  20551. this.getForRender( renderObject );
  20552. }
  20553. /**
  20554. * Returns a compute pipeline for the given parameters.
  20555. *
  20556. * @private
  20557. * @param {Node} computeNode - The compute node.
  20558. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20559. * @param {string} cacheKey - The cache key.
  20560. * @param {Array<BindGroup>} bindings - The bindings.
  20561. * @return {ComputePipeline} The compute pipeline.
  20562. */
  20563. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  20564. // check for existing pipeline
  20565. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  20566. let pipeline = this.caches.get( cacheKey );
  20567. if ( pipeline === undefined ) {
  20568. pipeline = new ComputePipeline( cacheKey, stageCompute );
  20569. this.caches.set( cacheKey, pipeline );
  20570. this.backend.createComputePipeline( pipeline, bindings );
  20571. }
  20572. return pipeline;
  20573. }
  20574. /**
  20575. * Returns a render pipeline for the given parameters.
  20576. *
  20577. * @private
  20578. * @param {RenderObject} renderObject - The render object.
  20579. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20580. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20581. * @param {string} cacheKey - The cache key.
  20582. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20583. * @return {ComputePipeline} The compute pipeline.
  20584. */
  20585. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  20586. // check for existing pipeline
  20587. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20588. let pipeline = this.caches.get( cacheKey );
  20589. if ( pipeline === undefined ) {
  20590. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  20591. this.caches.set( cacheKey, pipeline );
  20592. renderObject.pipeline = pipeline;
  20593. // The `promises` array is `null` by default and only set to an empty array when
  20594. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  20595. // pending promises that resolve when the render pipelines are ready for rendering.
  20596. this.backend.createRenderPipeline( renderObject, promises );
  20597. }
  20598. return pipeline;
  20599. }
  20600. /**
  20601. * Computes a cache key representing a compute pipeline.
  20602. *
  20603. * @private
  20604. * @param {Node} computeNode - The compute node.
  20605. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20606. * @return {string} The cache key.
  20607. */
  20608. _getComputeCacheKey( computeNode, stageCompute ) {
  20609. return computeNode.id + ',' + stageCompute.id;
  20610. }
  20611. /**
  20612. * Computes a cache key representing a render pipeline.
  20613. *
  20614. * @private
  20615. * @param {RenderObject} renderObject - The render object.
  20616. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20617. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20618. * @return {string} The cache key.
  20619. */
  20620. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  20621. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  20622. }
  20623. /**
  20624. * Releases the given pipeline.
  20625. *
  20626. * @private
  20627. * @param {Pipeline} pipeline - The pipeline to release.
  20628. */
  20629. _releasePipeline( pipeline ) {
  20630. this.caches.delete( pipeline.cacheKey );
  20631. }
  20632. /**
  20633. * Releases the shader program.
  20634. *
  20635. * @private
  20636. * @param {Object} program - The shader program to release.
  20637. */
  20638. _releaseProgram( program ) {
  20639. const code = program.code;
  20640. const stage = program.stage;
  20641. this.programs[ stage ].delete( code );
  20642. }
  20643. /**
  20644. * Returns `true` if the compute pipeline for the given compute node requires an update.
  20645. *
  20646. * @private
  20647. * @param {Node} computeNode - The compute node.
  20648. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  20649. */
  20650. _needsComputeUpdate( computeNode ) {
  20651. const data = this.get( computeNode );
  20652. return data.pipeline === undefined || data.version !== computeNode.version;
  20653. }
  20654. /**
  20655. * Returns `true` if the render pipeline for the given render object requires an update.
  20656. *
  20657. * @private
  20658. * @param {RenderObject} renderObject - The render object.
  20659. * @return {boolean} Whether the render object for the given render object requires an update or not.
  20660. */
  20661. _needsRenderUpdate( renderObject ) {
  20662. const data = this.get( renderObject );
  20663. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  20664. }
  20665. }
  20666. /**
  20667. * This renderer module manages the bindings of the renderer.
  20668. *
  20669. * @private
  20670. * @augments DataMap
  20671. */
  20672. class Bindings extends DataMap {
  20673. /**
  20674. * Constructs a new bindings management component.
  20675. *
  20676. * @param {Backend} backend - The renderer's backend.
  20677. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20678. * @param {Textures} textures - Renderer component for managing textures.
  20679. * @param {Attributes} attributes - Renderer component for managing attributes.
  20680. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20681. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20682. */
  20683. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  20684. super();
  20685. /**
  20686. * The renderer's backend.
  20687. *
  20688. * @type {Backend}
  20689. */
  20690. this.backend = backend;
  20691. /**
  20692. * Renderer component for managing textures.
  20693. *
  20694. * @type {Textures}
  20695. */
  20696. this.textures = textures;
  20697. /**
  20698. * Renderer component for managing pipelines.
  20699. *
  20700. * @type {Pipelines}
  20701. */
  20702. this.pipelines = pipelines;
  20703. /**
  20704. * Renderer component for managing attributes.
  20705. *
  20706. * @type {Attributes}
  20707. */
  20708. this.attributes = attributes;
  20709. /**
  20710. * Renderer component for managing nodes related logic.
  20711. *
  20712. * @type {Nodes}
  20713. */
  20714. this.nodes = nodes;
  20715. /**
  20716. * Renderer component for managing metrics and monitoring data.
  20717. *
  20718. * @type {Info}
  20719. */
  20720. this.info = info;
  20721. this.pipelines.bindings = this; // assign bindings to pipelines
  20722. }
  20723. /**
  20724. * Returns the bind groups for the given render object.
  20725. *
  20726. * @param {RenderObject} renderObject - The render object.
  20727. * @return {Array<BindGroup>} The bind groups.
  20728. */
  20729. getForRender( renderObject ) {
  20730. const bindings = renderObject.getBindings();
  20731. for ( const bindGroup of bindings ) {
  20732. const groupData = this.get( bindGroup );
  20733. if ( groupData.bindGroup === undefined ) {
  20734. // each object defines an array of bindings (ubos, textures, samplers etc.)
  20735. this._init( bindGroup );
  20736. this.backend.createBindings( bindGroup, bindings, 0 );
  20737. groupData.bindGroup = bindGroup;
  20738. }
  20739. }
  20740. return bindings;
  20741. }
  20742. /**
  20743. * Returns the bind groups for the given compute node.
  20744. *
  20745. * @param {Node} computeNode - The compute node.
  20746. * @return {Array<BindGroup>} The bind groups.
  20747. */
  20748. getForCompute( computeNode ) {
  20749. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  20750. for ( const bindGroup of bindings ) {
  20751. const groupData = this.get( bindGroup );
  20752. if ( groupData.bindGroup === undefined ) {
  20753. this._init( bindGroup );
  20754. this.backend.createBindings( bindGroup, bindings, 0 );
  20755. groupData.bindGroup = bindGroup;
  20756. }
  20757. }
  20758. return bindings;
  20759. }
  20760. /**
  20761. * Updates the bindings for the given compute node.
  20762. *
  20763. * @param {Node} computeNode - The compute node.
  20764. */
  20765. updateForCompute( computeNode ) {
  20766. this._updateBindings( this.getForCompute( computeNode ) );
  20767. }
  20768. /**
  20769. * Updates the bindings for the given render object.
  20770. *
  20771. * @param {RenderObject} renderObject - The render object.
  20772. */
  20773. updateForRender( renderObject ) {
  20774. this._updateBindings( this.getForRender( renderObject ) );
  20775. }
  20776. /**
  20777. * Updates the given array of bindings.
  20778. *
  20779. * @param {Array<BindGroup>} bindings - The bind groups.
  20780. */
  20781. _updateBindings( bindings ) {
  20782. for ( const bindGroup of bindings ) {
  20783. this._update( bindGroup, bindings );
  20784. }
  20785. }
  20786. /**
  20787. * Initializes the given bind group.
  20788. *
  20789. * @param {BindGroup} bindGroup - The bind group to initialize.
  20790. */
  20791. _init( bindGroup ) {
  20792. for ( const binding of bindGroup.bindings ) {
  20793. if ( binding.isSampledTexture ) {
  20794. this.textures.updateTexture( binding.texture );
  20795. } else if ( binding.isStorageBuffer ) {
  20796. const attribute = binding.attribute;
  20797. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20798. this.attributes.update( attribute, attributeType );
  20799. }
  20800. }
  20801. }
  20802. /**
  20803. * Updates the given bind group.
  20804. *
  20805. * @param {BindGroup} bindGroup - The bind group to update.
  20806. * @param {Array<BindGroup>} bindings - The bind groups.
  20807. */
  20808. _update( bindGroup, bindings ) {
  20809. const { backend } = this;
  20810. let needsBindingsUpdate = false;
  20811. let cacheBindings = true;
  20812. let cacheIndex = 0;
  20813. let version = 0;
  20814. // iterate over all bindings and check if buffer updates or a new binding group is required
  20815. for ( const binding of bindGroup.bindings ) {
  20816. if ( binding.isNodeUniformsGroup ) {
  20817. const updated = this.nodes.updateGroup( binding );
  20818. // every uniforms group is a uniform buffer. So if no update is required,
  20819. // we move one with the next binding. Otherwise the next if block will update the group.
  20820. if ( updated === false ) continue;
  20821. }
  20822. if ( binding.isStorageBuffer ) {
  20823. const attribute = binding.attribute;
  20824. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20825. this.attributes.update( attribute, attributeType );
  20826. }
  20827. if ( binding.isUniformBuffer ) {
  20828. const updated = binding.update();
  20829. if ( updated ) {
  20830. backend.updateBinding( binding );
  20831. }
  20832. } else if ( binding.isSampledTexture ) {
  20833. const updated = binding.update();
  20834. // get the texture data after the update, to sync the texture reference from node
  20835. const texture = binding.texture;
  20836. const texturesTextureData = this.textures.get( texture );
  20837. if ( updated ) {
  20838. // version: update the texture data or create a new one
  20839. this.textures.updateTexture( texture );
  20840. // generation: update the bindings if a new texture has been created
  20841. if ( binding.generation !== texturesTextureData.generation ) {
  20842. binding.generation = texturesTextureData.generation;
  20843. needsBindingsUpdate = true;
  20844. }
  20845. }
  20846. const textureData = backend.get( texture );
  20847. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  20848. cacheBindings = false;
  20849. } else {
  20850. cacheIndex = cacheIndex * 10 + texture.id;
  20851. version += texture.version;
  20852. }
  20853. if ( texture.isStorageTexture === true ) {
  20854. const textureData = this.get( texture );
  20855. if ( binding.store === true ) {
  20856. textureData.needsMipmap = true;
  20857. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  20858. this.backend.generateMipmaps( texture );
  20859. textureData.needsMipmap = false;
  20860. }
  20861. }
  20862. } else if ( binding.isSampler ) {
  20863. binding.update();
  20864. }
  20865. }
  20866. if ( needsBindingsUpdate === true ) {
  20867. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  20868. }
  20869. }
  20870. }
  20871. /**
  20872. * Default sorting function for opaque render items.
  20873. *
  20874. * @private
  20875. * @function
  20876. * @param {Object} a - The first render item.
  20877. * @param {Object} b - The second render item.
  20878. * @return {number} A numeric value which defines the sort order.
  20879. */
  20880. function painterSortStable( a, b ) {
  20881. if ( a.groupOrder !== b.groupOrder ) {
  20882. return a.groupOrder - b.groupOrder;
  20883. } else if ( a.renderOrder !== b.renderOrder ) {
  20884. return a.renderOrder - b.renderOrder;
  20885. } else if ( a.z !== b.z ) {
  20886. return a.z - b.z;
  20887. } else {
  20888. return a.id - b.id;
  20889. }
  20890. }
  20891. /**
  20892. * Default sorting function for transparent render items.
  20893. *
  20894. * @private
  20895. * @function
  20896. * @param {Object} a - The first render item.
  20897. * @param {Object} b - The second render item.
  20898. * @return {number} A numeric value which defines the sort order.
  20899. */
  20900. function reversePainterSortStable( a, b ) {
  20901. if ( a.groupOrder !== b.groupOrder ) {
  20902. return a.groupOrder - b.groupOrder;
  20903. } else if ( a.renderOrder !== b.renderOrder ) {
  20904. return a.renderOrder - b.renderOrder;
  20905. } else if ( a.z !== b.z ) {
  20906. return b.z - a.z;
  20907. } else {
  20908. return a.id - b.id;
  20909. }
  20910. }
  20911. /**
  20912. * Returns `true` if the given transparent material requires a double pass.
  20913. *
  20914. * @private
  20915. * @function
  20916. * @param {Material} material - The transparent material.
  20917. * @return {boolean} Whether the given material requires a double pass or not.
  20918. */
  20919. function needsDoublePass( material ) {
  20920. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  20921. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  20922. }
  20923. /**
  20924. * When the renderer analyzes the scene at the beginning of a render call,
  20925. * it stores 3D object for further processing in render lists. Depending on the
  20926. * properties of a 3D objects (like their transformation or material state), the
  20927. * objects are maintained in ordered lists for the actual rendering.
  20928. *
  20929. * Render lists are unique per scene and camera combination.
  20930. *
  20931. * @private
  20932. * @augments Pipeline
  20933. */
  20934. class RenderList {
  20935. /**
  20936. * Constructs a render list.
  20937. *
  20938. * @param {Lighting} lighting - The lighting management component.
  20939. * @param {Scene} scene - The scene.
  20940. * @param {Camera} camera - The camera the scene is rendered with.
  20941. */
  20942. constructor( lighting, scene, camera ) {
  20943. /**
  20944. * 3D objects are transformed into render items and stored in this array.
  20945. *
  20946. * @type {Array<Object>}
  20947. */
  20948. this.renderItems = [];
  20949. /**
  20950. * The current render items index.
  20951. *
  20952. * @type {number}
  20953. * @default 0
  20954. */
  20955. this.renderItemsIndex = 0;
  20956. /**
  20957. * A list with opaque render items.
  20958. *
  20959. * @type {Array<Object>}
  20960. */
  20961. this.opaque = [];
  20962. /**
  20963. * A list with transparent render items which require
  20964. * double pass rendering (e.g. transmissive objects).
  20965. *
  20966. * @type {Array<Object>}
  20967. */
  20968. this.transparentDoublePass = [];
  20969. /**
  20970. * A list with transparent render items.
  20971. *
  20972. * @type {Array<Object>}
  20973. */
  20974. this.transparent = [];
  20975. /**
  20976. * A list with transparent render bundle data.
  20977. *
  20978. * @type {Array<Object>}
  20979. */
  20980. this.bundles = [];
  20981. /**
  20982. * The render list's lights node. This node is later
  20983. * relevant for the actual analytical light nodes which
  20984. * compute the scene's lighting in the shader.
  20985. *
  20986. * @type {LightsNode}
  20987. */
  20988. this.lightsNode = lighting.getNode( scene, camera );
  20989. /**
  20990. * The scene's lights stored in an array. This array
  20991. * is used to setup the lights node.
  20992. *
  20993. * @type {Array<Light>}
  20994. */
  20995. this.lightsArray = [];
  20996. /**
  20997. * The scene.
  20998. *
  20999. * @type {Scene}
  21000. */
  21001. this.scene = scene;
  21002. /**
  21003. * The camera the scene is rendered with.
  21004. *
  21005. * @type {Camera}
  21006. */
  21007. this.camera = camera;
  21008. /**
  21009. * How many objects perform occlusion query tests.
  21010. *
  21011. * @type {number}
  21012. * @default 0
  21013. */
  21014. this.occlusionQueryCount = 0;
  21015. }
  21016. /**
  21017. * This method is called right at the beginning of a render call
  21018. * before the scene is analyzed. It prepares the internal data
  21019. * structures for the upcoming render lists generation.
  21020. *
  21021. * @return {RenderList} A reference to this render list.
  21022. */
  21023. begin() {
  21024. this.renderItemsIndex = 0;
  21025. this.opaque.length = 0;
  21026. this.transparentDoublePass.length = 0;
  21027. this.transparent.length = 0;
  21028. this.bundles.length = 0;
  21029. this.lightsArray.length = 0;
  21030. this.occlusionQueryCount = 0;
  21031. return this;
  21032. }
  21033. /**
  21034. * Returns a render item for the giving render item state. The state is defined
  21035. * by a series of object-related parameters.
  21036. *
  21037. * The method avoids object creation by holding render items and reusing them in
  21038. * subsequent render calls (just with different property values).
  21039. *
  21040. * @param {Object3D} object - The 3D object.
  21041. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21042. * @param {Material} material - The 3D object's material.
  21043. * @param {number} groupOrder - The current group order.
  21044. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21045. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21046. * @param {ClippingContext} clippingContext - The current clipping context.
  21047. * @return {Object} The render item.
  21048. */
  21049. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21050. let renderItem = this.renderItems[ this.renderItemsIndex ];
  21051. if ( renderItem === undefined ) {
  21052. renderItem = {
  21053. id: object.id,
  21054. object: object,
  21055. geometry: geometry,
  21056. material: material,
  21057. groupOrder: groupOrder,
  21058. renderOrder: object.renderOrder,
  21059. z: z,
  21060. group: group,
  21061. clippingContext: clippingContext
  21062. };
  21063. this.renderItems[ this.renderItemsIndex ] = renderItem;
  21064. } else {
  21065. renderItem.id = object.id;
  21066. renderItem.object = object;
  21067. renderItem.geometry = geometry;
  21068. renderItem.material = material;
  21069. renderItem.groupOrder = groupOrder;
  21070. renderItem.renderOrder = object.renderOrder;
  21071. renderItem.z = z;
  21072. renderItem.group = group;
  21073. renderItem.clippingContext = clippingContext;
  21074. }
  21075. this.renderItemsIndex ++;
  21076. return renderItem;
  21077. }
  21078. /**
  21079. * Pushes the given object as a render item to the internal render lists.
  21080. * The selected lists depend on the object properties.
  21081. *
  21082. * @param {Object3D} object - The 3D object.
  21083. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21084. * @param {Material} material - The 3D object's material.
  21085. * @param {number} groupOrder - The current group order.
  21086. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21087. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21088. * @param {ClippingContext} clippingContext - The current clipping context.
  21089. */
  21090. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21091. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21092. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  21093. if ( material.transparent === true || material.transmission > 0 ) {
  21094. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  21095. this.transparent.push( renderItem );
  21096. } else {
  21097. this.opaque.push( renderItem );
  21098. }
  21099. }
  21100. /**
  21101. * Inserts the given object as a render item at the start of the internal render lists.
  21102. * The selected lists depend on the object properties.
  21103. *
  21104. * @param {Object3D} object - The 3D object.
  21105. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21106. * @param {Material} material - The 3D object's material.
  21107. * @param {number} groupOrder - The current group order.
  21108. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21109. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21110. * @param {ClippingContext} clippingContext - The current clipping context.
  21111. */
  21112. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21113. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21114. if ( material.transparent === true || material.transmission > 0 ) {
  21115. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  21116. this.transparent.unshift( renderItem );
  21117. } else {
  21118. this.opaque.unshift( renderItem );
  21119. }
  21120. }
  21121. /**
  21122. * Pushes render bundle group data into the render list.
  21123. *
  21124. * @param {Object} group - Bundle group data.
  21125. */
  21126. pushBundle( group ) {
  21127. this.bundles.push( group );
  21128. }
  21129. /**
  21130. * Pushes a light into the render list.
  21131. *
  21132. * @param {Light} light - The light.
  21133. */
  21134. pushLight( light ) {
  21135. this.lightsArray.push( light );
  21136. }
  21137. /**
  21138. * Sorts the internal render lists.
  21139. *
  21140. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  21141. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  21142. */
  21143. sort( customOpaqueSort, customTransparentSort ) {
  21144. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  21145. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  21146. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  21147. }
  21148. /**
  21149. * This method performs finalizing tasks right after the render lists
  21150. * have been generated.
  21151. */
  21152. finish() {
  21153. // update lights
  21154. this.lightsNode.setLights( this.lightsArray );
  21155. // Clear references from inactive renderItems in the list
  21156. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  21157. const renderItem = this.renderItems[ i ];
  21158. if ( renderItem.id === null ) break;
  21159. renderItem.id = null;
  21160. renderItem.object = null;
  21161. renderItem.geometry = null;
  21162. renderItem.material = null;
  21163. renderItem.groupOrder = null;
  21164. renderItem.renderOrder = null;
  21165. renderItem.z = null;
  21166. renderItem.group = null;
  21167. renderItem.clippingContext = null;
  21168. }
  21169. }
  21170. }
  21171. const _chainKeys$4 = [];
  21172. /**
  21173. * This renderer module manages the render lists which are unique
  21174. * per scene and camera combination.
  21175. *
  21176. * @private
  21177. */
  21178. class RenderLists {
  21179. /**
  21180. * Constructs a render lists management component.
  21181. *
  21182. * @param {Lighting} lighting - The lighting management component.
  21183. */
  21184. constructor( lighting ) {
  21185. /**
  21186. * The lighting management component.
  21187. *
  21188. * @type {Lighting}
  21189. */
  21190. this.lighting = lighting;
  21191. /**
  21192. * The internal chain map which holds the render lists.
  21193. *
  21194. * @type {ChainMap}
  21195. */
  21196. this.lists = new ChainMap();
  21197. }
  21198. /**
  21199. * Returns a render list for the given scene and camera.
  21200. *
  21201. * @param {Scene} scene - The scene.
  21202. * @param {Camera} camera - The camera.
  21203. * @return {RenderList} The render list.
  21204. */
  21205. get( scene, camera ) {
  21206. const lists = this.lists;
  21207. _chainKeys$4[ 0 ] = scene;
  21208. _chainKeys$4[ 1 ] = camera;
  21209. let list = lists.get( _chainKeys$4 );
  21210. if ( list === undefined ) {
  21211. list = new RenderList( this.lighting, scene, camera );
  21212. lists.set( _chainKeys$4, list );
  21213. }
  21214. _chainKeys$4.length = 0;
  21215. return list;
  21216. }
  21217. /**
  21218. * Frees all internal resources.
  21219. */
  21220. dispose() {
  21221. this.lists = new ChainMap();
  21222. }
  21223. }
  21224. let _id$7 = 0;
  21225. /**
  21226. * Any render or compute command is executed in a specific context that defines
  21227. * the state of the renderer and its backend. Typical examples for such context
  21228. * data are the current clear values or data from the active framebuffer. This
  21229. * module is used to represent these contexts as objects.
  21230. *
  21231. * @private
  21232. */
  21233. class RenderContext {
  21234. /**
  21235. * Constructs a new render context.
  21236. */
  21237. constructor() {
  21238. /**
  21239. * The context's ID.
  21240. *
  21241. * @type {number}
  21242. */
  21243. this.id = _id$7 ++;
  21244. /**
  21245. * Whether the current active framebuffer has a color attachment.
  21246. *
  21247. * @type {boolean}
  21248. * @default true
  21249. */
  21250. this.color = true;
  21251. /**
  21252. * Whether the color attachment should be cleared or not.
  21253. *
  21254. * @type {boolean}
  21255. * @default true
  21256. */
  21257. this.clearColor = true;
  21258. /**
  21259. * The clear color value.
  21260. *
  21261. * @type {Object}
  21262. * @default true
  21263. */
  21264. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  21265. /**
  21266. * Whether the current active framebuffer has a depth attachment.
  21267. *
  21268. * @type {boolean}
  21269. * @default true
  21270. */
  21271. this.depth = true;
  21272. /**
  21273. * Whether the depth attachment should be cleared or not.
  21274. *
  21275. * @type {boolean}
  21276. * @default true
  21277. */
  21278. this.clearDepth = true;
  21279. /**
  21280. * The clear depth value.
  21281. *
  21282. * @type {number}
  21283. * @default 1
  21284. */
  21285. this.clearDepthValue = 1;
  21286. /**
  21287. * Whether the current active framebuffer has a stencil attachment.
  21288. *
  21289. * @type {boolean}
  21290. * @default false
  21291. */
  21292. this.stencil = false;
  21293. /**
  21294. * Whether the stencil attachment should be cleared or not.
  21295. *
  21296. * @type {boolean}
  21297. * @default true
  21298. */
  21299. this.clearStencil = true;
  21300. /**
  21301. * The clear stencil value.
  21302. *
  21303. * @type {number}
  21304. * @default 1
  21305. */
  21306. this.clearStencilValue = 1;
  21307. /**
  21308. * By default the viewport encloses the entire framebuffer If a smaller
  21309. * viewport is manually defined, this property is to `true` by the renderer.
  21310. *
  21311. * @type {boolean}
  21312. * @default false
  21313. */
  21314. this.viewport = false;
  21315. /**
  21316. * The viewport value. This value is in physical pixels meaning it incorporates
  21317. * the renderer's pixel ratio. The viewport property of render targets or
  21318. * the renderer is in logical pixels.
  21319. *
  21320. * @type {Vector4}
  21321. */
  21322. this.viewportValue = new Vector4();
  21323. /**
  21324. * When the scissor test is active and scissor rectangle smaller than the
  21325. * framebuffers dimensions, this property is to `true` by the renderer.
  21326. *
  21327. * @type {boolean}
  21328. * @default false
  21329. */
  21330. this.scissor = false;
  21331. /**
  21332. * The scissor rectangle.
  21333. *
  21334. * @type {Vector4}
  21335. */
  21336. this.scissorValue = new Vector4();
  21337. /**
  21338. * The active render target.
  21339. *
  21340. * @type {?RenderTarget}
  21341. * @default null
  21342. */
  21343. this.renderTarget = null;
  21344. /**
  21345. * The textures of the active render target.
  21346. * `null` when no render target is set.
  21347. *
  21348. * @type {?Array<Texture>}
  21349. * @default null
  21350. */
  21351. this.textures = null;
  21352. /**
  21353. * The depth texture of the active render target.
  21354. * `null` when no render target is set.
  21355. *
  21356. * @type {?DepthTexture}
  21357. * @default null
  21358. */
  21359. this.depthTexture = null;
  21360. /**
  21361. * The active cube face.
  21362. *
  21363. * @type {number}
  21364. * @default 0
  21365. */
  21366. this.activeCubeFace = 0;
  21367. /**
  21368. * The active mipmap level.
  21369. *
  21370. * @type {number}
  21371. * @default 0
  21372. */
  21373. this.activeMipmapLevel = 0;
  21374. /**
  21375. * The number of MSAA samples. This value is always `1` when
  21376. * MSAA isn't used.
  21377. *
  21378. * @type {number}
  21379. * @default 1
  21380. */
  21381. this.sampleCount = 1;
  21382. /**
  21383. * The active render target's width in physical pixels.
  21384. *
  21385. * @type {number}
  21386. * @default 0
  21387. */
  21388. this.width = 0;
  21389. /**
  21390. * The active render target's height in physical pixels.
  21391. *
  21392. * @type {number}
  21393. * @default 0
  21394. */
  21395. this.height = 0;
  21396. /**
  21397. * The occlusion query count.
  21398. *
  21399. * @type {number}
  21400. * @default 0
  21401. */
  21402. this.occlusionQueryCount = 0;
  21403. /**
  21404. * The current clipping context.
  21405. *
  21406. * @type {?ClippingContext}
  21407. * @default null
  21408. */
  21409. this.clippingContext = null;
  21410. /**
  21411. * This flag can be used for type testing.
  21412. *
  21413. * @type {boolean}
  21414. * @readonly
  21415. * @default true
  21416. */
  21417. this.isRenderContext = true;
  21418. }
  21419. /**
  21420. * Returns the cache key of this render context.
  21421. *
  21422. * @return {number} The cache key.
  21423. */
  21424. getCacheKey() {
  21425. return getCacheKey( this );
  21426. }
  21427. }
  21428. /**
  21429. * Computes a cache key for the given render context. This key
  21430. * should identify the render target state so it is possible to
  21431. * configure the correct attachments in the respective backend.
  21432. *
  21433. * @param {RenderContext} renderContext - The render context.
  21434. * @return {number} The cache key.
  21435. */
  21436. function getCacheKey( renderContext ) {
  21437. const { textures, activeCubeFace } = renderContext;
  21438. const values = [ activeCubeFace ];
  21439. for ( const texture of textures ) {
  21440. values.push( texture.id );
  21441. }
  21442. return hashArray( values );
  21443. }
  21444. const _chainKeys$3 = [];
  21445. const _defaultScene = /*@__PURE__*/ new Scene();
  21446. const _defaultCamera = /*@__PURE__*/ new Camera();
  21447. /**
  21448. * This module manages the render contexts of the renderer.
  21449. *
  21450. * @private
  21451. */
  21452. class RenderContexts {
  21453. /**
  21454. * Constructs a new render context management component.
  21455. */
  21456. constructor() {
  21457. /**
  21458. * A dictionary that manages render contexts in chain maps
  21459. * for each attachment state.
  21460. *
  21461. * @type {Object<string,ChainMap>}
  21462. */
  21463. this.chainMaps = {};
  21464. }
  21465. /**
  21466. * Returns a render context for the given scene, camera and render target.
  21467. *
  21468. * @param {Scene} scene - The scene.
  21469. * @param {Camera} camera - The camera that is used to render the scene.
  21470. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21471. * @return {RenderContext} The render context.
  21472. */
  21473. get( scene, camera, renderTarget = null ) {
  21474. _chainKeys$3[ 0 ] = scene;
  21475. _chainKeys$3[ 1 ] = camera;
  21476. let attachmentState;
  21477. if ( renderTarget === null ) {
  21478. attachmentState = 'default';
  21479. } else {
  21480. const format = renderTarget.texture.format;
  21481. const count = renderTarget.textures.length;
  21482. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  21483. }
  21484. const chainMap = this._getChainMap( attachmentState );
  21485. let renderState = chainMap.get( _chainKeys$3 );
  21486. if ( renderState === undefined ) {
  21487. renderState = new RenderContext();
  21488. chainMap.set( _chainKeys$3, renderState );
  21489. }
  21490. _chainKeys$3.length = 0;
  21491. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21492. return renderState;
  21493. }
  21494. /**
  21495. * Returns a render context intended for clear operations.
  21496. *
  21497. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21498. * @return {RenderContext} The render context.
  21499. */
  21500. getForClear( renderTarget = null ) {
  21501. return this.get( _defaultScene, _defaultCamera, renderTarget );
  21502. }
  21503. /**
  21504. * Returns a chain map for the given attachment state.
  21505. *
  21506. * @private
  21507. * @param {string} attachmentState - The attachment state.
  21508. * @return {ChainMap} The chain map.
  21509. */
  21510. _getChainMap( attachmentState ) {
  21511. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  21512. }
  21513. /**
  21514. * Frees internal resources.
  21515. */
  21516. dispose() {
  21517. this.chainMaps = {};
  21518. }
  21519. }
  21520. const _size$3 = /*@__PURE__*/ new Vector3();
  21521. /**
  21522. * This module manages the textures of the renderer.
  21523. *
  21524. * @private
  21525. * @augments DataMap
  21526. */
  21527. class Textures extends DataMap {
  21528. /**
  21529. * Constructs a new texture management component.
  21530. *
  21531. * @param {Renderer} renderer - The renderer.
  21532. * @param {Backend} backend - The renderer's backend.
  21533. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21534. */
  21535. constructor( renderer, backend, info ) {
  21536. super();
  21537. /**
  21538. * The renderer.
  21539. *
  21540. * @type {Renderer}
  21541. */
  21542. this.renderer = renderer;
  21543. /**
  21544. * The backend.
  21545. *
  21546. * @type {Backend}
  21547. */
  21548. this.backend = backend;
  21549. /**
  21550. * Renderer component for managing metrics and monitoring data.
  21551. *
  21552. * @type {Info}
  21553. */
  21554. this.info = info;
  21555. }
  21556. /**
  21557. * Updates the given render target. Based on the given render target configuration,
  21558. * it updates the texture states representing the attachments of the framebuffer.
  21559. *
  21560. * @param {RenderTarget} renderTarget - The render target to update.
  21561. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  21562. */
  21563. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  21564. const renderTargetData = this.get( renderTarget );
  21565. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21566. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  21567. const textures = renderTarget.textures;
  21568. const size = this.getSize( textures[ 0 ] );
  21569. const mipWidth = size.width >> activeMipmapLevel;
  21570. const mipHeight = size.height >> activeMipmapLevel;
  21571. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  21572. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  21573. let textureNeedsUpdate = false;
  21574. if ( depthTexture === undefined && useDepthTexture ) {
  21575. depthTexture = new DepthTexture();
  21576. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  21577. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  21578. depthTexture.image.width = mipWidth;
  21579. depthTexture.image.height = mipHeight;
  21580. depthTexture.image.depth = size.depth;
  21581. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  21582. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  21583. }
  21584. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  21585. textureNeedsUpdate = true;
  21586. if ( depthTexture ) {
  21587. depthTexture.needsUpdate = true;
  21588. depthTexture.image.width = mipWidth;
  21589. depthTexture.image.height = mipHeight;
  21590. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  21591. }
  21592. }
  21593. renderTargetData.width = size.width;
  21594. renderTargetData.height = size.height;
  21595. renderTargetData.textures = textures;
  21596. renderTargetData.depthTexture = depthTexture || null;
  21597. renderTargetData.depth = renderTarget.depthBuffer;
  21598. renderTargetData.stencil = renderTarget.stencilBuffer;
  21599. renderTargetData.renderTarget = renderTarget;
  21600. if ( renderTargetData.sampleCount !== sampleCount ) {
  21601. textureNeedsUpdate = true;
  21602. if ( depthTexture ) {
  21603. depthTexture.needsUpdate = true;
  21604. }
  21605. renderTargetData.sampleCount = sampleCount;
  21606. }
  21607. //
  21608. const options = { sampleCount };
  21609. // XR render targets require no texture updates
  21610. if ( renderTarget.isXRRenderTarget !== true ) {
  21611. for ( let i = 0; i < textures.length; i ++ ) {
  21612. const texture = textures[ i ];
  21613. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  21614. this.updateTexture( texture, options );
  21615. }
  21616. if ( depthTexture ) {
  21617. this.updateTexture( depthTexture, options );
  21618. }
  21619. }
  21620. // dispose handler
  21621. if ( renderTargetData.initialized !== true ) {
  21622. renderTargetData.initialized = true;
  21623. // dispose
  21624. const onDispose = () => {
  21625. renderTarget.removeEventListener( 'dispose', onDispose );
  21626. for ( let i = 0; i < textures.length; i ++ ) {
  21627. this._destroyTexture( textures[ i ] );
  21628. }
  21629. if ( depthTexture ) {
  21630. this._destroyTexture( depthTexture );
  21631. }
  21632. this.delete( renderTarget );
  21633. };
  21634. renderTarget.addEventListener( 'dispose', onDispose );
  21635. }
  21636. }
  21637. /**
  21638. * Updates the given texture. Depending on the texture state, this method
  21639. * triggers the upload of texture data to the GPU memory. If the texture data are
  21640. * not yet ready for the upload, it uses default texture data for as a placeholder.
  21641. *
  21642. * @param {Texture} texture - The texture to update.
  21643. * @param {Object} [options={}] - The options.
  21644. */
  21645. updateTexture( texture, options = {} ) {
  21646. const textureData = this.get( texture );
  21647. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  21648. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  21649. const backend = this.backend;
  21650. if ( isRenderTarget && textureData.initialized === true ) {
  21651. // it's an update
  21652. backend.destroySampler( texture );
  21653. backend.destroyTexture( texture );
  21654. }
  21655. //
  21656. if ( texture.isFramebufferTexture ) {
  21657. const renderTarget = this.renderer.getRenderTarget();
  21658. if ( renderTarget ) {
  21659. texture.type = renderTarget.texture.type;
  21660. } else {
  21661. texture.type = UnsignedByteType;
  21662. }
  21663. }
  21664. //
  21665. const { width, height, depth } = this.getSize( texture );
  21666. options.width = width;
  21667. options.height = height;
  21668. options.depth = depth;
  21669. options.needsMipmaps = this.needsMipmaps( texture );
  21670. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  21671. //
  21672. if ( isRenderTarget || texture.isStorageTexture === true ) {
  21673. backend.createSampler( texture );
  21674. backend.createTexture( texture, options );
  21675. textureData.generation = texture.version;
  21676. } else {
  21677. const needsCreate = textureData.initialized !== true;
  21678. if ( needsCreate ) backend.createSampler( texture );
  21679. if ( texture.version > 0 ) {
  21680. const image = texture.image;
  21681. if ( image === undefined ) {
  21682. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  21683. } else if ( image.complete === false ) {
  21684. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  21685. } else {
  21686. if ( texture.images ) {
  21687. const images = [];
  21688. for ( const image of texture.images ) {
  21689. images.push( image );
  21690. }
  21691. options.images = images;
  21692. } else {
  21693. options.image = image;
  21694. }
  21695. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  21696. backend.createTexture( texture, options );
  21697. textureData.isDefaultTexture = false;
  21698. textureData.generation = texture.version;
  21699. }
  21700. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  21701. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  21702. }
  21703. } else {
  21704. // async update
  21705. backend.createDefaultTexture( texture );
  21706. textureData.isDefaultTexture = true;
  21707. textureData.generation = texture.version;
  21708. }
  21709. }
  21710. // dispose handler
  21711. if ( textureData.initialized !== true ) {
  21712. textureData.initialized = true;
  21713. textureData.generation = texture.version;
  21714. //
  21715. this.info.memory.textures ++;
  21716. // dispose
  21717. const onDispose = () => {
  21718. texture.removeEventListener( 'dispose', onDispose );
  21719. this._destroyTexture( texture );
  21720. };
  21721. texture.addEventListener( 'dispose', onDispose );
  21722. }
  21723. //
  21724. textureData.version = texture.version;
  21725. }
  21726. /**
  21727. * Computes the size of the given texture and writes the result
  21728. * into the target vector. This vector is also returned by the
  21729. * method.
  21730. *
  21731. * If no texture data are available for the compute yet, the method
  21732. * returns default size values.
  21733. *
  21734. * @param {Texture} texture - The texture to compute the size for.
  21735. * @param {Vector3} target - The target vector.
  21736. * @return {Vector3} The target vector.
  21737. */
  21738. getSize( texture, target = _size$3 ) {
  21739. let image = texture.images ? texture.images[ 0 ] : texture.image;
  21740. if ( image ) {
  21741. if ( image.image !== undefined ) image = image.image;
  21742. if ( image instanceof HTMLVideoElement ) {
  21743. target.width = image.videoWidth || 1;
  21744. target.height = image.videoHeight || 1;
  21745. target.depth = 1;
  21746. } else if ( image instanceof VideoFrame ) {
  21747. target.width = image.displayWidth || 1;
  21748. target.height = image.displayHeight || 1;
  21749. target.depth = 1;
  21750. } else {
  21751. target.width = image.width || 1;
  21752. target.height = image.height || 1;
  21753. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  21754. }
  21755. } else {
  21756. target.width = target.height = target.depth = 1;
  21757. }
  21758. return target;
  21759. }
  21760. /**
  21761. * Computes the number of mipmap levels for the given texture.
  21762. *
  21763. * @param {Texture} texture - The texture.
  21764. * @param {number} width - The texture's width.
  21765. * @param {number} height - The texture's height.
  21766. * @return {number} The number of mipmap levels.
  21767. */
  21768. getMipLevels( texture, width, height ) {
  21769. let mipLevelCount;
  21770. if ( texture.isCompressedTexture ) {
  21771. if ( texture.mipmaps ) {
  21772. mipLevelCount = texture.mipmaps.length;
  21773. } else {
  21774. mipLevelCount = 1;
  21775. }
  21776. } else {
  21777. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  21778. }
  21779. return mipLevelCount;
  21780. }
  21781. /**
  21782. * Returns `true` if the given texture requires mipmaps.
  21783. *
  21784. * @param {Texture} texture - The texture.
  21785. * @return {boolean} Whether mipmaps are required or not.
  21786. */
  21787. needsMipmaps( texture ) {
  21788. return texture.isCompressedTexture === true || texture.generateMipmaps;
  21789. }
  21790. /**
  21791. * Frees internal resource when the given texture isn't
  21792. * required anymore.
  21793. *
  21794. * @param {Texture} texture - The texture to destroy.
  21795. */
  21796. _destroyTexture( texture ) {
  21797. if ( this.has( texture ) === true ) {
  21798. this.backend.destroySampler( texture );
  21799. this.backend.destroyTexture( texture );
  21800. this.delete( texture );
  21801. this.info.memory.textures --;
  21802. }
  21803. }
  21804. }
  21805. /**
  21806. * A four-component version of {@link Color} which is internally
  21807. * used by the renderer to represents clear color with alpha as
  21808. * one object.
  21809. *
  21810. * @private
  21811. * @augments Color
  21812. */
  21813. class Color4 extends Color {
  21814. /**
  21815. * Constructs a new four-component color.
  21816. * You can also pass a single THREE.Color, hex or
  21817. * string argument to this constructor.
  21818. *
  21819. * @param {number|string} [r=1] - The red value.
  21820. * @param {number} [g=1] - The green value.
  21821. * @param {number} [b=1] - The blue value.
  21822. * @param {number} [a=1] - The alpha value.
  21823. */
  21824. constructor( r, g, b, a = 1 ) {
  21825. super( r, g, b );
  21826. this.a = a;
  21827. }
  21828. /**
  21829. * Overwrites the default to honor alpha.
  21830. * You can also pass a single THREE.Color, hex or
  21831. * string argument to this method.
  21832. *
  21833. * @param {number|string|Color} r - The red value.
  21834. * @param {number} [g] - The green value.
  21835. * @param {number} [b] - The blue value.
  21836. * @param {number} [a=1] - The alpha value.
  21837. * @return {Color4} A reference to this object.
  21838. */
  21839. set( r, g, b, a = 1 ) {
  21840. this.a = a;
  21841. return super.set( r, g, b );
  21842. }
  21843. /**
  21844. * Overwrites the default to honor alpha.
  21845. *
  21846. * @param {Color4} color - The color to copy.
  21847. * @return {Color4} A reference to this object.
  21848. */
  21849. copy( color ) {
  21850. if ( color.a !== undefined ) this.a = color.a;
  21851. return super.copy( color );
  21852. }
  21853. /**
  21854. * Overwrites the default to honor alpha.
  21855. *
  21856. * @return {Color4} The cloned color.
  21857. */
  21858. clone() {
  21859. return new this.constructor( this.r, this.g, this.b, this.a );
  21860. }
  21861. }
  21862. /**
  21863. * Special version of {@link PropertyNode} which is used for parameters.
  21864. *
  21865. * @augments PropertyNode
  21866. */
  21867. class ParameterNode extends PropertyNode {
  21868. static get type() {
  21869. return 'ParameterNode';
  21870. }
  21871. /**
  21872. * Constructs a new parameter node.
  21873. *
  21874. * @param {string} nodeType - The type of the node.
  21875. * @param {?string} [name=null] - The name of the parameter in the shader.
  21876. */
  21877. constructor( nodeType, name = null ) {
  21878. super( nodeType, name );
  21879. /**
  21880. * This flag can be used for type testing.
  21881. *
  21882. * @type {boolean}
  21883. * @readonly
  21884. * @default true
  21885. */
  21886. this.isParameterNode = true;
  21887. }
  21888. getHash() {
  21889. return this.uuid;
  21890. }
  21891. generate() {
  21892. return this.name;
  21893. }
  21894. }
  21895. /**
  21896. * TSL function for creating a parameter node.
  21897. *
  21898. * @tsl
  21899. * @function
  21900. * @param {string} type - The type of the node.
  21901. * @param {?string} name - The name of the parameter in the shader.
  21902. * @returns {ParameterNode}
  21903. */
  21904. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  21905. /**
  21906. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  21907. * They are usually needed in cases like `If`, `Else`.
  21908. *
  21909. * @augments Node
  21910. */
  21911. class StackNode extends Node {
  21912. static get type() {
  21913. return 'StackNode';
  21914. }
  21915. /**
  21916. * Constructs a new stack node.
  21917. *
  21918. * @param {?StackNode} [parent=null] - The parent stack node.
  21919. */
  21920. constructor( parent = null ) {
  21921. super();
  21922. /**
  21923. * List of nodes.
  21924. *
  21925. * @type {Array<Node>}
  21926. */
  21927. this.nodes = [];
  21928. /**
  21929. * The output node.
  21930. *
  21931. * @type {?Node}
  21932. * @default null
  21933. */
  21934. this.outputNode = null;
  21935. /**
  21936. * The parent stack node.
  21937. *
  21938. * @type {?StackNode}
  21939. * @default null
  21940. */
  21941. this.parent = parent;
  21942. /**
  21943. * The current conditional node.
  21944. *
  21945. * @private
  21946. * @type {ConditionalNode}
  21947. * @default null
  21948. */
  21949. this._currentCond = null;
  21950. /**
  21951. * The expression node. Only
  21952. * relevant for Switch/Case.
  21953. *
  21954. * @private
  21955. * @type {Node}
  21956. * @default null
  21957. */
  21958. this._expressionNode = null;
  21959. /**
  21960. * This flag can be used for type testing.
  21961. *
  21962. * @type {boolean}
  21963. * @readonly
  21964. * @default true
  21965. */
  21966. this.isStackNode = true;
  21967. }
  21968. getNodeType( builder ) {
  21969. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  21970. }
  21971. getMemberType( builder, name ) {
  21972. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  21973. }
  21974. /**
  21975. * Adds a node to this stack.
  21976. *
  21977. * @param {Node} node - The node to add.
  21978. * @return {StackNode} A reference to this stack node.
  21979. */
  21980. add( node ) {
  21981. this.nodes.push( node );
  21982. return this;
  21983. }
  21984. /**
  21985. * Represent an `if` statement in TSL.
  21986. *
  21987. * @param {Node} boolNode - Represents the condition.
  21988. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21989. * @return {StackNode} A reference to this stack node.
  21990. */
  21991. If( boolNode, method ) {
  21992. const methodNode = new ShaderNode( method );
  21993. this._currentCond = select( boolNode, methodNode );
  21994. return this.add( this._currentCond );
  21995. }
  21996. /**
  21997. * Represent an `elseif` statement in TSL.
  21998. *
  21999. * @param {Node} boolNode - Represents the condition.
  22000. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22001. * @return {StackNode} A reference to this stack node.
  22002. */
  22003. ElseIf( boolNode, method ) {
  22004. const methodNode = new ShaderNode( method );
  22005. const ifNode = select( boolNode, methodNode );
  22006. this._currentCond.elseNode = ifNode;
  22007. this._currentCond = ifNode;
  22008. return this;
  22009. }
  22010. /**
  22011. * Represent an `else` statement in TSL.
  22012. *
  22013. * @param {Function} method - TSL code which is executed in the `else` case.
  22014. * @return {StackNode} A reference to this stack node.
  22015. */
  22016. Else( method ) {
  22017. this._currentCond.elseNode = new ShaderNode( method );
  22018. return this;
  22019. }
  22020. /**
  22021. * Represents a `switch` statement in TSL.
  22022. *
  22023. * @param {any} expression - Represents the expression.
  22024. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22025. * @return {StackNode} A reference to this stack node.
  22026. */
  22027. Switch( expression ) {
  22028. this._expressionNode = nodeObject( expression );
  22029. return this;
  22030. }
  22031. /**
  22032. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  22033. * The last parameter must be the callback method that should be executed in the `true` case.
  22034. *
  22035. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  22036. * @return {StackNode} A reference to this stack node.
  22037. */
  22038. Case( ...params ) {
  22039. const caseNodes = [];
  22040. // extract case nodes from the parameter list
  22041. if ( params.length >= 2 ) {
  22042. for ( let i = 0; i < params.length - 1; i ++ ) {
  22043. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  22044. }
  22045. } else {
  22046. throw new Error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  22047. }
  22048. // extract method
  22049. const method = params[ params.length - 1 ];
  22050. const methodNode = new ShaderNode( method );
  22051. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  22052. let caseNode = caseNodes[ 0 ];
  22053. for ( let i = 1; i < caseNodes.length; i ++ ) {
  22054. caseNode = caseNode.or( caseNodes[ i ] );
  22055. }
  22056. // build condition
  22057. const condNode = select( caseNode, methodNode );
  22058. if ( this._currentCond === null ) {
  22059. this._currentCond = condNode;
  22060. return this.add( this._currentCond );
  22061. } else {
  22062. this._currentCond.elseNode = condNode;
  22063. this._currentCond = condNode;
  22064. return this;
  22065. }
  22066. }
  22067. /**
  22068. * Represents the default code block of a Switch/Case statement.
  22069. *
  22070. * @param {Function} method - TSL code which is executed in the `else` case.
  22071. * @return {StackNode} A reference to this stack node.
  22072. */
  22073. Default( method ) {
  22074. this.Else( method );
  22075. return this;
  22076. }
  22077. setup( builder ) {
  22078. const nodeProperties = builder.getNodeProperties( this );
  22079. let index = 0;
  22080. for ( const childNode of this.getChildren() ) {
  22081. if ( childNode.isVarNode && childNode.intent === true ) {
  22082. const properties = builder.getNodeProperties( childNode );
  22083. if ( properties.assign !== true ) {
  22084. continue;
  22085. }
  22086. }
  22087. nodeProperties[ 'node' + index ++ ] = childNode;
  22088. }
  22089. // return a outputNode if exists or null
  22090. return nodeProperties.outputNode || null;
  22091. }
  22092. build( builder, ...params ) {
  22093. const previousBuildStack = builder.currentStack;
  22094. const previousStack = getCurrentStack();
  22095. setCurrentStack( this );
  22096. builder.currentStack = this;
  22097. const buildStage = builder.buildStage;
  22098. for ( const node of this.nodes ) {
  22099. if ( node.isVarNode && node.intent === true ) {
  22100. const properties = builder.getNodeProperties( node );
  22101. if ( properties.assign !== true ) {
  22102. continue;
  22103. }
  22104. }
  22105. if ( buildStage === 'setup' ) {
  22106. node.build( builder );
  22107. } else if ( buildStage === 'analyze' ) {
  22108. node.build( builder, this );
  22109. } else if ( buildStage === 'generate' ) {
  22110. const stages = builder.getDataFromNode( node, 'any' ).stages;
  22111. const parents = stages && stages[ builder.shaderStage ];
  22112. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  22113. continue; // skip var nodes that are only used in .toVarying()
  22114. }
  22115. node.build( builder, 'void' );
  22116. }
  22117. }
  22118. const result = this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  22119. setCurrentStack( previousStack );
  22120. builder.currentStack = previousBuildStack;
  22121. return result;
  22122. }
  22123. }
  22124. /**
  22125. * TSL function for creating a stack node.
  22126. *
  22127. * @tsl
  22128. * @function
  22129. * @param {?StackNode} [parent=null] - The parent stack node.
  22130. * @returns {StackNode}
  22131. */
  22132. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  22133. /**
  22134. * Generates a layout for struct members.
  22135. * This function takes an object representing struct members and returns an array of member layouts.
  22136. * Each member layout includes the member's name, type, and whether it is atomic.
  22137. *
  22138. * @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.
  22139. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  22140. */
  22141. function getMembersLayout( members ) {
  22142. return Object.entries( members ).map( ( [ name, value ] ) => {
  22143. if ( typeof value === 'string' ) {
  22144. return { name, type: value, atomic: false };
  22145. }
  22146. return { name, type: value.type, atomic: value.atomic || false };
  22147. } );
  22148. }
  22149. /**
  22150. * Represents a struct type node in the node-based system.
  22151. * This class is used to define and manage the layout and types of struct members.
  22152. * It extends the base Node class and provides methods to get the length of the struct,
  22153. * retrieve member types, and generate the struct type for a builder.
  22154. *
  22155. * @augments Node
  22156. */
  22157. class StructTypeNode extends Node {
  22158. static get type() {
  22159. return 'StructTypeNode';
  22160. }
  22161. /**
  22162. * Creates an instance of StructTypeNode.
  22163. *
  22164. * @param {Object} membersLayout - The layout of the members for the struct.
  22165. * @param {?string} [name=null] - The optional name of the struct.
  22166. */
  22167. constructor( membersLayout, name = null ) {
  22168. super( 'struct' );
  22169. /**
  22170. * The layout of the members for the struct
  22171. *
  22172. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  22173. */
  22174. this.membersLayout = getMembersLayout( membersLayout );
  22175. /**
  22176. * The name of the struct.
  22177. *
  22178. * @type {?string}
  22179. * @default null
  22180. */
  22181. this.name = name;
  22182. /**
  22183. * This flag can be used for type testing.
  22184. *
  22185. * @type {boolean}
  22186. * @readonly
  22187. * @default true
  22188. */
  22189. this.isStructLayoutNode = true;
  22190. }
  22191. /**
  22192. * Returns the length of the struct.
  22193. * The length is calculated by summing the lengths of the struct's members.
  22194. *
  22195. * @returns {number} The length of the struct.
  22196. */
  22197. getLength() {
  22198. const GPU_CHUNK_BYTES = 8;
  22199. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  22200. let offset = 0; // global buffer offset in bytes
  22201. for ( const member of this.membersLayout ) {
  22202. const type = member.type;
  22203. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  22204. const boundary = getByteBoundaryFromType( type );
  22205. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  22206. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  22207. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  22208. offset += chunkPadding;
  22209. // Check for chunk overflow
  22210. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  22211. // Add padding to the end of the chunk
  22212. offset += ( GPU_CHUNK_BYTES - chunkStart );
  22213. }
  22214. offset += itemSize;
  22215. }
  22216. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  22217. }
  22218. getMemberType( builder, name ) {
  22219. const member = this.membersLayout.find( m => m.name === name );
  22220. return member ? member.type : 'void';
  22221. }
  22222. getNodeType( builder ) {
  22223. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  22224. return structType.name;
  22225. }
  22226. setup( builder ) {
  22227. builder.addInclude( this );
  22228. }
  22229. generate( builder ) {
  22230. return this.getNodeType( builder );
  22231. }
  22232. }
  22233. /**
  22234. * StructNode allows to create custom structures with multiple members.
  22235. * This can also be used to define structures in attribute and uniform data.
  22236. *
  22237. * ```js
  22238. * // Define a custom struct
  22239. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  22240. *
  22241. * // Create a new instance of the struct
  22242. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  22243. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  22244. *
  22245. * // Access the struct members
  22246. * const min = bb.get( 'min' );
  22247. *
  22248. * // Assign a new value to a member
  22249. * min.assign( vec3() );
  22250. * ```
  22251. * @augments Node
  22252. */
  22253. class StructNode extends Node {
  22254. static get type() {
  22255. return 'StructNode';
  22256. }
  22257. constructor( structLayoutNode, values ) {
  22258. super( 'vec3' );
  22259. this.structLayoutNode = structLayoutNode;
  22260. this.values = values;
  22261. this.isStructNode = true;
  22262. }
  22263. getNodeType( builder ) {
  22264. return this.structLayoutNode.getNodeType( builder );
  22265. }
  22266. getMemberType( builder, name ) {
  22267. return this.structLayoutNode.getMemberType( builder, name );
  22268. }
  22269. generate( builder ) {
  22270. const nodeVar = builder.getVarFromNode( this );
  22271. const structType = nodeVar.type;
  22272. const propertyName = builder.getPropertyName( nodeVar );
  22273. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  22274. return nodeVar.name;
  22275. }
  22276. }
  22277. /**
  22278. * TSL function for creating a struct node.
  22279. *
  22280. * @tsl
  22281. * @function
  22282. * @param {Object} membersLayout - The layout of the struct members.
  22283. * @param {?string} [name=null] - The name of the struct.
  22284. * @returns {Function} The struct function.
  22285. */
  22286. const struct = ( membersLayout, name = null ) => {
  22287. const structLayout = new StructTypeNode( membersLayout, name );
  22288. const struct = ( ...params ) => {
  22289. let values = null;
  22290. if ( params.length > 0 ) {
  22291. if ( params[ 0 ].isNode ) {
  22292. values = {};
  22293. const names = Object.keys( membersLayout );
  22294. for ( let i = 0; i < params.length; i ++ ) {
  22295. values[ names[ i ] ] = params[ i ];
  22296. }
  22297. } else {
  22298. values = params[ 0 ];
  22299. }
  22300. }
  22301. return nodeObject( new StructNode( structLayout, values ) );
  22302. };
  22303. struct.layout = structLayout;
  22304. struct.isStruct = true;
  22305. return struct;
  22306. };
  22307. /**
  22308. * This node can be used to define multiple outputs in a shader programs.
  22309. *
  22310. * @augments Node
  22311. */
  22312. class OutputStructNode extends Node {
  22313. static get type() {
  22314. return 'OutputStructNode';
  22315. }
  22316. /**
  22317. * Constructs a new output struct node. The constructor can be invoked with an
  22318. * arbitrary number of nodes representing the members.
  22319. *
  22320. * @param {...Node} members - A parameter list of nodes.
  22321. */
  22322. constructor( ...members ) {
  22323. super();
  22324. /**
  22325. * An array of nodes which defines the output.
  22326. *
  22327. * @type {Array<Node>}
  22328. */
  22329. this.members = members;
  22330. /**
  22331. * This flag can be used for type testing.
  22332. *
  22333. * @type {boolean}
  22334. * @readonly
  22335. * @default true
  22336. */
  22337. this.isOutputStructNode = true;
  22338. }
  22339. getNodeType( builder ) {
  22340. const properties = builder.getNodeProperties( this );
  22341. if ( properties.membersLayout === undefined ) {
  22342. const members = this.members;
  22343. const membersLayout = [];
  22344. for ( let i = 0; i < members.length; i ++ ) {
  22345. const name = 'm' + i;
  22346. const type = members[ i ].getNodeType( builder );
  22347. membersLayout.push( { name, type, index: i } );
  22348. }
  22349. properties.membersLayout = membersLayout;
  22350. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  22351. }
  22352. return properties.structType.name;
  22353. }
  22354. generate( builder ) {
  22355. const propertyName = builder.getOutputStructName();
  22356. const members = this.members;
  22357. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  22358. for ( let i = 0; i < members.length; i ++ ) {
  22359. const snippet = members[ i ].build( builder );
  22360. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  22361. }
  22362. return propertyName;
  22363. }
  22364. }
  22365. /**
  22366. * TSL function for creating an output struct node.
  22367. *
  22368. * @tsl
  22369. * @function
  22370. * @param {...Node} members - A parameter list of nodes.
  22371. * @returns {OutputStructNode}
  22372. */
  22373. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  22374. /**
  22375. * Returns the MRT texture index for the given name.
  22376. *
  22377. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  22378. * @param {string} name - The name of the MRT texture which index is requested.
  22379. * @return {number} The texture index.
  22380. */
  22381. function getTextureIndex( textures, name ) {
  22382. for ( let i = 0; i < textures.length; i ++ ) {
  22383. if ( textures[ i ].name === name ) {
  22384. return i;
  22385. }
  22386. }
  22387. return -1;
  22388. }
  22389. /**
  22390. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  22391. * post-processing is shown below:
  22392. * ```js
  22393. * const mrtNode = mrt( {
  22394. * output: output,
  22395. * normal: normalView
  22396. * } ) );
  22397. * ```
  22398. * The MRT output is defined as a dictionary.
  22399. *
  22400. * @augments OutputStructNode
  22401. */
  22402. class MRTNode extends OutputStructNode {
  22403. static get type() {
  22404. return 'MRTNode';
  22405. }
  22406. /**
  22407. * Constructs a new output struct node.
  22408. *
  22409. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22410. */
  22411. constructor( outputNodes ) {
  22412. super();
  22413. /**
  22414. * A dictionary representing the MRT outputs. The key
  22415. * is the name of the output, the value the node which produces
  22416. * the output result.
  22417. *
  22418. * @type {Object<string, Node>}
  22419. */
  22420. this.outputNodes = outputNodes;
  22421. /**
  22422. * This flag can be used for type testing.
  22423. *
  22424. * @type {boolean}
  22425. * @readonly
  22426. * @default true
  22427. */
  22428. this.isMRTNode = true;
  22429. }
  22430. /**
  22431. * Returns `true` if the MRT node has an output with the given name.
  22432. *
  22433. * @param {string} name - The name of the output.
  22434. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  22435. */
  22436. has( name ) {
  22437. return this.outputNodes[ name ] !== undefined;
  22438. }
  22439. /**
  22440. * Returns the output node for the given name.
  22441. *
  22442. * @param {string} name - The name of the output.
  22443. * @return {Node} The output node.
  22444. */
  22445. get( name ) {
  22446. return this.outputNodes[ name ];
  22447. }
  22448. /**
  22449. * Merges the outputs of the given MRT node with the outputs of this node.
  22450. *
  22451. * @param {MRTNode} mrtNode - The MRT to merge.
  22452. * @return {MRTNode} A new MRT node with merged outputs..
  22453. */
  22454. merge( mrtNode ) {
  22455. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  22456. return mrt( outputs );
  22457. }
  22458. setup( builder ) {
  22459. const outputNodes = this.outputNodes;
  22460. const mrt = builder.renderer.getRenderTarget();
  22461. const members = [];
  22462. const textures = mrt.textures;
  22463. for ( const name in outputNodes ) {
  22464. const index = getTextureIndex( textures, name );
  22465. members[ index ] = vec4( outputNodes[ name ] );
  22466. }
  22467. this.members = members;
  22468. return super.setup( builder );
  22469. }
  22470. }
  22471. /**
  22472. * TSL function for creating a MRT node.
  22473. *
  22474. * @tsl
  22475. * @function
  22476. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22477. * @returns {MRTNode}
  22478. */
  22479. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  22480. /**
  22481. * Generates a hash value in the range `[0, 1]` from the given seed.
  22482. *
  22483. * @tsl
  22484. * @function
  22485. * @param {Node<float>} seed - The seed.
  22486. * @return {Node<float>} The hash value.
  22487. */
  22488. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  22489. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  22490. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  22491. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  22492. const result = word.shiftRight( 22 ).bitXor( word );
  22493. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  22494. } );
  22495. /**
  22496. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22497. * The corners are mapped to `0` and the center to `1`.
  22498. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22499. *
  22500. * @tsl
  22501. * @function
  22502. * @param {Node<float>} x - The value to remap.
  22503. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  22504. * @return {Node<float>} The remapped value.
  22505. */
  22506. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  22507. /**
  22508. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22509. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  22510. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22511. *
  22512. * @tsl
  22513. * @function
  22514. * @param {Node<float>} x - The value to remap.
  22515. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  22516. * @return {Node<float>} The remapped value.
  22517. */
  22518. 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 ) );
  22519. /**
  22520. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22521. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  22522. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22523. *
  22524. * @tsl
  22525. * @function
  22526. * @param {Node<float>} x - The value to remap.
  22527. * @param {Node<float>} a - First control parameter.
  22528. * @param {Node<float>} b - Second control parameter.
  22529. * @return {Node<float>} The remapped value.
  22530. */
  22531. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  22532. /**
  22533. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  22534. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22535. *
  22536. * @tsl
  22537. * @function
  22538. * @param {Node<float>} x - The value to compute the sin for.
  22539. * @param {Node<float>} k - Controls the amount of bounces.
  22540. * @return {Node<float>} The result value.
  22541. */
  22542. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  22543. // https://github.com/cabbibo/glsl-tri-noise-3d
  22544. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  22545. return x.fract().sub( .5 ).abs();
  22546. } ).setLayout( {
  22547. name: 'tri',
  22548. type: 'float',
  22549. inputs: [
  22550. { name: 'x', type: 'float' }
  22551. ]
  22552. } );
  22553. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  22554. 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. ) ) ) ) );
  22555. } ).setLayout( {
  22556. name: 'tri3',
  22557. type: 'vec3',
  22558. inputs: [
  22559. { name: 'p', type: 'vec3' }
  22560. ]
  22561. } );
  22562. /**
  22563. * Generates a noise value from the given position, speed and time parameters.
  22564. *
  22565. * @tsl
  22566. * @function
  22567. * @param {Node<vec3>} position - The position.
  22568. * @param {Node<float>} speed - The speed.
  22569. * @param {Node<float>} time - The time.
  22570. * @return {Node<float>} The generated noise.
  22571. */
  22572. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  22573. const p = vec3( position ).toVar();
  22574. const z = float( 1.4 ).toVar();
  22575. const rz = float( 0.0 ).toVar();
  22576. const bp = vec3( p ).toVar();
  22577. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  22578. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  22579. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  22580. bp.mulAssign( 1.8 );
  22581. z.mulAssign( 1.5 );
  22582. p.mulAssign( 1.2 );
  22583. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  22584. rz.addAssign( t.div( z ) );
  22585. bp.addAssign( 0.14 );
  22586. } );
  22587. return rz;
  22588. } ).setLayout( {
  22589. name: 'triNoise3D',
  22590. type: 'float',
  22591. inputs: [
  22592. { name: 'position', type: 'vec3' },
  22593. { name: 'speed', type: 'float' },
  22594. { name: 'time', type: 'float' }
  22595. ]
  22596. } );
  22597. /**
  22598. * This class allows to define multiple overloaded versions
  22599. * of the same function. Depending on the parameters of the function
  22600. * call, the node picks the best-fit overloaded version.
  22601. *
  22602. * @augments Node
  22603. */
  22604. class FunctionOverloadingNode extends Node {
  22605. static get type() {
  22606. return 'FunctionOverloadingNode';
  22607. }
  22608. /**
  22609. * Constructs a new function overloading node.
  22610. *
  22611. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22612. * @param {...Node} parametersNodes - A list of parameter nodes.
  22613. */
  22614. constructor( functionNodes = [], ...parametersNodes ) {
  22615. super();
  22616. /**
  22617. * Array of `Fn` function definitions.
  22618. *
  22619. * @type {Array<Function>}
  22620. */
  22621. this.functionNodes = functionNodes;
  22622. /**
  22623. * A list of parameter nodes.
  22624. *
  22625. * @type {Array<Node>}
  22626. */
  22627. this.parametersNodes = parametersNodes;
  22628. /**
  22629. * The selected overloaded function call.
  22630. *
  22631. * @private
  22632. * @type {ShaderCallNodeInternal}
  22633. */
  22634. this._candidateFnCall = null;
  22635. /**
  22636. * This node is marked as global.
  22637. *
  22638. * @type {boolean}
  22639. * @default true
  22640. */
  22641. this.global = true;
  22642. }
  22643. /**
  22644. * This method is overwritten since the node type is inferred from
  22645. * the function's return type.
  22646. *
  22647. * @param {NodeBuilder} builder - The current node builder.
  22648. * @return {string} The node type.
  22649. */
  22650. getNodeType() {
  22651. return this.functionNodes[ 0 ].shaderNode.layout.type;
  22652. }
  22653. setup( builder ) {
  22654. const params = this.parametersNodes;
  22655. let candidateFnCall = this._candidateFnCall;
  22656. if ( candidateFnCall === null ) {
  22657. let candidateFn = null;
  22658. let candidateScore = -1;
  22659. for ( const functionNode of this.functionNodes ) {
  22660. const shaderNode = functionNode.shaderNode;
  22661. const layout = shaderNode.layout;
  22662. if ( layout === null ) {
  22663. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  22664. }
  22665. const inputs = layout.inputs;
  22666. if ( params.length === inputs.length ) {
  22667. let score = 0;
  22668. for ( let i = 0; i < params.length; i ++ ) {
  22669. const param = params[ i ];
  22670. const input = inputs[ i ];
  22671. if ( param.getNodeType( builder ) === input.type ) {
  22672. score ++;
  22673. } else {
  22674. score = 0;
  22675. }
  22676. }
  22677. if ( score > candidateScore ) {
  22678. candidateFn = functionNode;
  22679. candidateScore = score;
  22680. }
  22681. }
  22682. }
  22683. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  22684. }
  22685. return candidateFnCall;
  22686. }
  22687. }
  22688. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  22689. /**
  22690. * TSL function for creating a function overloading node.
  22691. *
  22692. * @tsl
  22693. * @function
  22694. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22695. * @returns {FunctionOverloadingNode}
  22696. */
  22697. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  22698. /**
  22699. * Represents the elapsed time in seconds.
  22700. *
  22701. * @tsl
  22702. * @type {UniformNode<float>}
  22703. */
  22704. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  22705. /**
  22706. * Represents the delta time in seconds.
  22707. *
  22708. * @tsl
  22709. * @type {UniformNode<float>}
  22710. */
  22711. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  22712. /**
  22713. * Represents the current frame ID.
  22714. *
  22715. * @tsl
  22716. * @type {UniformNode<uint>}
  22717. */
  22718. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  22719. // Deprecated
  22720. /**
  22721. * @tsl
  22722. * @function
  22723. * @deprecated since r170. Use {@link time} instead.
  22724. *
  22725. * @param {number} [timeScale=1] - The time scale.
  22726. * @returns {UniformNode<float>}
  22727. */
  22728. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  22729. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  22730. return time.mul( timeScale );
  22731. };
  22732. /**
  22733. * @tsl
  22734. * @function
  22735. * @deprecated since r170. Use {@link time} instead.
  22736. *
  22737. * @param {number} [timeScale=1] - The time scale.
  22738. * @returns {UniformNode<float>}
  22739. */
  22740. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  22741. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  22742. return time.mul( timeScale );
  22743. };
  22744. /**
  22745. * @tsl
  22746. * @function
  22747. * @deprecated since r170. Use {@link deltaTime} instead.
  22748. *
  22749. * @param {number} [timeScale=1] - The time scale.
  22750. * @returns {UniformNode<float>}
  22751. */
  22752. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  22753. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  22754. return deltaTime.mul( timeScale );
  22755. };
  22756. /**
  22757. * Generates a sine wave oscillation based on a timer.
  22758. *
  22759. * @tsl
  22760. * @function
  22761. * @param {Node<float>} t - The timer to generate the oscillation with.
  22762. * @return {Node<float>} The oscillation node.
  22763. */
  22764. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  22765. /**
  22766. * Generates a square wave oscillation based on a timer.
  22767. *
  22768. * @tsl
  22769. * @function
  22770. * @param {Node<float>} t - The timer to generate the oscillation with.
  22771. * @return {Node<float>} The oscillation node.
  22772. */
  22773. const oscSquare = ( t = time ) => t.fract().round();
  22774. /**
  22775. * Generates a triangle wave oscillation based on a timer.
  22776. *
  22777. * @tsl
  22778. * @function
  22779. * @param {Node<float>} t - The timer to generate the oscillation with.
  22780. * @return {Node<float>} The oscillation node.
  22781. */
  22782. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  22783. /**
  22784. * Generates a sawtooth wave oscillation based on a timer.
  22785. *
  22786. * @tsl
  22787. * @function
  22788. * @param {Node<float>} t - The timer to generate the oscillation with.
  22789. * @return {Node<float>} The oscillation node.
  22790. */
  22791. const oscSawtooth = ( t = time ) => t.fract();
  22792. /**
  22793. * Rotates the given uv coordinates around a center point
  22794. *
  22795. * @tsl
  22796. * @function
  22797. * @param {Node<vec2>} uv - The uv coordinates.
  22798. * @param {Node<float>} rotation - The rotation defined in radians.
  22799. * @param {Node<vec2>} center - The center of rotation
  22800. * @return {Node<vec2>} The rotated uv coordinates.
  22801. */
  22802. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  22803. return rotate( uv.sub( center ), rotation ).add( center );
  22804. } );
  22805. /**
  22806. * Applies a spherical warping effect to the given uv coordinates.
  22807. *
  22808. * @tsl
  22809. * @function
  22810. * @param {Node<vec2>} uv - The uv coordinates.
  22811. * @param {Node<float>} strength - The strength of the effect.
  22812. * @param {Node<vec2>} center - The center point
  22813. * @return {Node<vec2>} The updated uv coordinates.
  22814. */
  22815. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  22816. const delta = uv.sub( center );
  22817. const delta2 = delta.dot( delta );
  22818. const delta4 = delta2.mul( delta2 );
  22819. const deltaOffset = delta4.mul( strength );
  22820. return uv.add( delta.mul( deltaOffset ) );
  22821. } );
  22822. /**
  22823. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  22824. * oriented always towards the camera.
  22825. *
  22826. * ```js
  22827. * material.vertexNode = billboarding();
  22828. * ```
  22829. *
  22830. * @tsl
  22831. * @function
  22832. * @param {Object} config - The configuration object.
  22833. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  22834. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  22835. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  22836. * @return {Node<vec3>} The updated vertex position in clip space.
  22837. */
  22838. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  22839. let worldMatrix;
  22840. if ( position !== null ) {
  22841. worldMatrix = modelWorldMatrix.toVar();
  22842. worldMatrix[ 3 ][ 0 ] = position.x;
  22843. worldMatrix[ 3 ][ 1 ] = position.y;
  22844. worldMatrix[ 3 ][ 2 ] = position.z;
  22845. } else {
  22846. worldMatrix = modelWorldMatrix;
  22847. }
  22848. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  22849. if ( defined( horizontal ) ) {
  22850. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  22851. modelViewMatrix[ 0 ][ 1 ] = 0;
  22852. modelViewMatrix[ 0 ][ 2 ] = 0;
  22853. }
  22854. if ( defined( vertical ) ) {
  22855. modelViewMatrix[ 1 ][ 0 ] = 0;
  22856. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  22857. modelViewMatrix[ 1 ][ 2 ] = 0;
  22858. }
  22859. modelViewMatrix[ 2 ][ 0 ] = 0;
  22860. modelViewMatrix[ 2 ][ 1 ] = 0;
  22861. modelViewMatrix[ 2 ][ 2 ] = 1;
  22862. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  22863. } );
  22864. /**
  22865. * A special version of a screen uv function that involves a depth comparison
  22866. * when computing the final uvs. The function mitigates visual errors when
  22867. * using viewport texture nodes for refraction purposes. Without this function
  22868. * objects in front of a refractive surface might appear on the refractive surface
  22869. * which is incorrect.
  22870. *
  22871. * @tsl
  22872. * @function
  22873. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  22874. * @return {Node<vec2>} The update uv coordinates.
  22875. */
  22876. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  22877. const depth = linearDepth();
  22878. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  22879. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  22880. return finalUV;
  22881. } );
  22882. /**
  22883. * Can be used to compute texture coordinates for animated sprite sheets.
  22884. *
  22885. * ```js
  22886. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  22887. *
  22888. * material.colorNode = texture( spriteSheet, uvNode );
  22889. * ```
  22890. *
  22891. * @augments Node
  22892. */
  22893. class SpriteSheetUVNode extends Node {
  22894. static get type() {
  22895. return 'SpriteSheetUVNode';
  22896. }
  22897. /**
  22898. * Constructs a new sprite sheet uv node.
  22899. *
  22900. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22901. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  22902. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22903. */
  22904. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  22905. super( 'vec2' );
  22906. /**
  22907. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22908. *
  22909. * @type {Node<vec2>}
  22910. */
  22911. this.countNode = countNode;
  22912. /**
  22913. * The uv node.
  22914. *
  22915. * @type {Node<vec2>}
  22916. */
  22917. this.uvNode = uvNode;
  22918. /**
  22919. * The node that defines the current frame/sprite.
  22920. *
  22921. * @type {Node<float>}
  22922. */
  22923. this.frameNode = frameNode;
  22924. }
  22925. setup() {
  22926. const { frameNode, uvNode, countNode } = this;
  22927. const { width, height } = countNode;
  22928. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  22929. const column = frameNum.mod( width );
  22930. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  22931. const scale = countNode.reciprocal();
  22932. const uvFrameOffset = vec2( column, row );
  22933. return uvNode.add( uvFrameOffset ).mul( scale );
  22934. }
  22935. }
  22936. /**
  22937. * TSL function for creating a sprite sheet uv node.
  22938. *
  22939. * @tsl
  22940. * @function
  22941. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22942. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  22943. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22944. * @returns {SpriteSheetUVNode}
  22945. */
  22946. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  22947. /**
  22948. * TSL function for creating a triplanar textures node.
  22949. *
  22950. * Can be used for triplanar texture mapping.
  22951. *
  22952. * ```js
  22953. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  22954. * ```
  22955. *
  22956. * @tsl
  22957. * @function
  22958. * @param {Node} textureXNode - First texture node.
  22959. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22960. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22961. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22962. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22963. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22964. * @returns {Node<vec4>}
  22965. */
  22966. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  22967. // Reference: https://github.com/keijiro/StandardTriplanar
  22968. // Blending factor of triplanar mapping
  22969. let bf = normalNode.abs().normalize();
  22970. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  22971. // Triplanar mapping
  22972. const tx = positionNode.yz.mul( scaleNode );
  22973. const ty = positionNode.zx.mul( scaleNode );
  22974. const tz = positionNode.xy.mul( scaleNode );
  22975. // Base color
  22976. const textureX = textureXNode.value;
  22977. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  22978. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  22979. const cx = texture( textureX, tx ).mul( bf.x );
  22980. const cy = texture( textureY, ty ).mul( bf.y );
  22981. const cz = texture( textureZ, tz ).mul( bf.z );
  22982. return add( cx, cy, cz );
  22983. } );
  22984. /**
  22985. * TSL function for creating a triplanar textures node.
  22986. *
  22987. * @tsl
  22988. * @function
  22989. * @param {Node} textureXNode - First texture node.
  22990. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22991. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22992. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22993. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22994. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22995. * @returns {Node<vec4>}
  22996. */
  22997. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  22998. const _reflectorPlane = new Plane();
  22999. const _normal = new Vector3();
  23000. const _reflectorWorldPosition = new Vector3();
  23001. const _cameraWorldPosition = new Vector3();
  23002. const _rotationMatrix = new Matrix4();
  23003. const _lookAtPosition = new Vector3( 0, 0, -1 );
  23004. const clipPlane = new Vector4();
  23005. const _view = new Vector3();
  23006. const _target = new Vector3();
  23007. const _q = new Vector4();
  23008. const _size$2 = new Vector2();
  23009. const _defaultRT = new RenderTarget();
  23010. const _defaultUV = screenUV.flipX();
  23011. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  23012. let _inReflector = false;
  23013. /**
  23014. * This node can be used to implement mirror-like flat reflective surfaces.
  23015. *
  23016. * ```js
  23017. * const groundReflector = reflector();
  23018. * material.colorNode = groundReflector;
  23019. *
  23020. * const plane = new Mesh( geometry, material );
  23021. * plane.add( groundReflector.target );
  23022. * ```
  23023. *
  23024. * @augments TextureNode
  23025. */
  23026. class ReflectorNode extends TextureNode {
  23027. static get type() {
  23028. return 'ReflectorNode';
  23029. }
  23030. /**
  23031. * Constructs a new reflector node.
  23032. *
  23033. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23034. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23035. * @param {number} [parameters.resolution=1] - The resolution scale.
  23036. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23037. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23038. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23039. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23040. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23041. */
  23042. constructor( parameters = {} ) {
  23043. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  23044. /**
  23045. * A reference to the internal reflector base node which holds the actual implementation.
  23046. *
  23047. * @private
  23048. * @type {ReflectorBaseNode}
  23049. * @default ReflectorBaseNode
  23050. */
  23051. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  23052. /**
  23053. * A reference to the internal depth node.
  23054. *
  23055. * @private
  23056. * @type {?Node}
  23057. * @default null
  23058. */
  23059. this._depthNode = null;
  23060. this.setUpdateMatrix( false );
  23061. }
  23062. /**
  23063. * A reference to the internal reflector node.
  23064. *
  23065. * @type {ReflectorBaseNode}
  23066. */
  23067. get reflector() {
  23068. return this._reflectorBaseNode;
  23069. }
  23070. /**
  23071. * A reference to 3D object the reflector is linked to.
  23072. *
  23073. * @type {Object3D}
  23074. */
  23075. get target() {
  23076. return this._reflectorBaseNode.target;
  23077. }
  23078. /**
  23079. * Returns a node representing the mirror's depth. That can be used
  23080. * to implement more advanced reflection effects like distance attenuation.
  23081. *
  23082. * @return {Node} The depth node.
  23083. */
  23084. getDepthNode() {
  23085. if ( this._depthNode === null ) {
  23086. if ( this._reflectorBaseNode.depth !== true ) {
  23087. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  23088. }
  23089. this._depthNode = nodeObject( new ReflectorNode( {
  23090. defaultTexture: _defaultRT.depthTexture,
  23091. reflector: this._reflectorBaseNode
  23092. } ) );
  23093. }
  23094. return this._depthNode;
  23095. }
  23096. setup( builder ) {
  23097. // ignore if used in post-processing
  23098. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  23099. return super.setup( builder );
  23100. }
  23101. clone() {
  23102. const newNode = new this.constructor( this.reflectorNode );
  23103. newNode.uvNode = this.uvNode;
  23104. newNode.levelNode = this.levelNode;
  23105. newNode.biasNode = this.biasNode;
  23106. newNode.sampler = this.sampler;
  23107. newNode.depthNode = this.depthNode;
  23108. newNode.compareNode = this.compareNode;
  23109. newNode.gradNode = this.gradNode;
  23110. newNode._reflectorBaseNode = this._reflectorBaseNode;
  23111. return newNode;
  23112. }
  23113. /**
  23114. * Frees internal resources. Should be called when the node is no longer in use.
  23115. */
  23116. dispose() {
  23117. super.dispose();
  23118. this._reflectorBaseNode.dispose();
  23119. }
  23120. }
  23121. /**
  23122. * Holds the actual implementation of the reflector.
  23123. *
  23124. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  23125. * in `ReflectorNode`, see #29619.
  23126. *
  23127. * @private
  23128. * @augments Node
  23129. */
  23130. class ReflectorBaseNode extends Node {
  23131. static get type() {
  23132. return 'ReflectorBaseNode';
  23133. }
  23134. /**
  23135. * Constructs a new reflector base node.
  23136. *
  23137. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  23138. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23139. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23140. * @param {number} [parameters.resolution=1] - The resolution scale.
  23141. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23142. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23143. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23144. */
  23145. constructor( textureNode, parameters = {} ) {
  23146. super();
  23147. const {
  23148. target = new Object3D(),
  23149. resolution = 1,
  23150. generateMipmaps = false,
  23151. bounces = true,
  23152. depth = false
  23153. } = parameters;
  23154. /**
  23155. * Represents the rendered reflections as a texture node.
  23156. *
  23157. * @type {TextureNode}
  23158. */
  23159. this.textureNode = textureNode;
  23160. /**
  23161. * The 3D object the reflector is linked to.
  23162. *
  23163. * @type {Object3D}
  23164. * @default {new Object3D()}
  23165. */
  23166. this.target = target;
  23167. /**
  23168. * The resolution scale.
  23169. *
  23170. * @type {number}
  23171. * @default {1}
  23172. */
  23173. this.resolution = resolution;
  23174. /**
  23175. * Whether mipmaps should be generated or not.
  23176. *
  23177. * @type {boolean}
  23178. * @default {false}
  23179. */
  23180. this.generateMipmaps = generateMipmaps;
  23181. /**
  23182. * Whether reflectors can render other reflector nodes or not.
  23183. *
  23184. * @type {boolean}
  23185. * @default {true}
  23186. */
  23187. this.bounces = bounces;
  23188. /**
  23189. * Whether depth data should be generated or not.
  23190. *
  23191. * @type {boolean}
  23192. * @default {false}
  23193. */
  23194. this.depth = depth;
  23195. /**
  23196. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  23197. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  23198. *
  23199. * @type {string}
  23200. * @default 'render'
  23201. */
  23202. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  23203. /**
  23204. * Weak map for managing virtual cameras.
  23205. *
  23206. * @type {WeakMap<Camera, Camera>}
  23207. */
  23208. this.virtualCameras = new WeakMap();
  23209. /**
  23210. * Weak map for managing render targets.
  23211. *
  23212. * @type {Map<Camera, RenderTarget>}
  23213. */
  23214. this.renderTargets = new Map();
  23215. /**
  23216. * Force render even if reflector is facing away from camera.
  23217. *
  23218. * @type {boolean}
  23219. * @default {false}
  23220. */
  23221. this.forceUpdate = false;
  23222. /**
  23223. * Whether the reflector has been rendered or not.
  23224. *
  23225. * When the reflector is facing away from the camera,
  23226. * this flag is set to `false` and the texture will be empty(black).
  23227. *
  23228. * @type {boolean}
  23229. * @default {false}
  23230. */
  23231. this.hasOutput = false;
  23232. }
  23233. /**
  23234. * Updates the resolution of the internal render target.
  23235. *
  23236. * @private
  23237. * @param {RenderTarget} renderTarget - The render target to resize.
  23238. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  23239. */
  23240. _updateResolution( renderTarget, renderer ) {
  23241. const resolution = this.resolution;
  23242. renderer.getDrawingBufferSize( _size$2 );
  23243. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  23244. }
  23245. setup( builder ) {
  23246. this._updateResolution( _defaultRT, builder.renderer );
  23247. return super.setup( builder );
  23248. }
  23249. /**
  23250. * Frees internal resources. Should be called when the node is no longer in use.
  23251. */
  23252. dispose() {
  23253. super.dispose();
  23254. for ( const renderTarget of this.renderTargets.values() ) {
  23255. renderTarget.dispose();
  23256. }
  23257. }
  23258. /**
  23259. * Returns a virtual camera for the given camera. The virtual camera is used to
  23260. * render the scene from the reflector's view so correct reflections can be produced.
  23261. *
  23262. * @param {Camera} camera - The scene's camera.
  23263. * @return {Camera} The corresponding virtual camera.
  23264. */
  23265. getVirtualCamera( camera ) {
  23266. let virtualCamera = this.virtualCameras.get( camera );
  23267. if ( virtualCamera === undefined ) {
  23268. virtualCamera = camera.clone();
  23269. this.virtualCameras.set( camera, virtualCamera );
  23270. }
  23271. return virtualCamera;
  23272. }
  23273. /**
  23274. * Returns a render target for the given camera. The reflections are rendered
  23275. * into this render target.
  23276. *
  23277. * @param {Camera} camera - The scene's camera.
  23278. * @return {RenderTarget} The render target.
  23279. */
  23280. getRenderTarget( camera ) {
  23281. let renderTarget = this.renderTargets.get( camera );
  23282. if ( renderTarget === undefined ) {
  23283. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  23284. if ( this.generateMipmaps === true ) {
  23285. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  23286. renderTarget.texture.generateMipmaps = true;
  23287. }
  23288. if ( this.depth === true ) {
  23289. renderTarget.depthTexture = new DepthTexture();
  23290. }
  23291. this.renderTargets.set( camera, renderTarget );
  23292. }
  23293. return renderTarget;
  23294. }
  23295. updateBefore( frame ) {
  23296. if ( this.bounces === false && _inReflector ) return false;
  23297. _inReflector = true;
  23298. const { scene, camera, renderer, material } = frame;
  23299. const { target } = this;
  23300. const virtualCamera = this.getVirtualCamera( camera );
  23301. const renderTarget = this.getRenderTarget( virtualCamera );
  23302. renderer.getDrawingBufferSize( _size$2 );
  23303. this._updateResolution( renderTarget, renderer );
  23304. //
  23305. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  23306. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  23307. _rotationMatrix.extractRotation( target.matrixWorld );
  23308. _normal.set( 0, 0, 1 );
  23309. _normal.applyMatrix4( _rotationMatrix );
  23310. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  23311. // Avoid rendering when reflector is facing away unless forcing an update
  23312. const isFacingAway = _view.dot( _normal ) > 0;
  23313. let needsClear = false;
  23314. if ( isFacingAway === true && this.forceUpdate === false ) {
  23315. if ( this.hasOutput === false ) {
  23316. _inReflector = false;
  23317. return;
  23318. }
  23319. needsClear = true;
  23320. }
  23321. _view.reflect( _normal ).negate();
  23322. _view.add( _reflectorWorldPosition );
  23323. _rotationMatrix.extractRotation( camera.matrixWorld );
  23324. _lookAtPosition.set( 0, 0, -1 );
  23325. _lookAtPosition.applyMatrix4( _rotationMatrix );
  23326. _lookAtPosition.add( _cameraWorldPosition );
  23327. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  23328. _target.reflect( _normal ).negate();
  23329. _target.add( _reflectorWorldPosition );
  23330. //
  23331. virtualCamera.coordinateSystem = camera.coordinateSystem;
  23332. virtualCamera.position.copy( _view );
  23333. virtualCamera.up.set( 0, 1, 0 );
  23334. virtualCamera.up.applyMatrix4( _rotationMatrix );
  23335. virtualCamera.up.reflect( _normal );
  23336. virtualCamera.lookAt( _target );
  23337. virtualCamera.near = camera.near;
  23338. virtualCamera.far = camera.far;
  23339. virtualCamera.updateMatrixWorld();
  23340. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  23341. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  23342. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  23343. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  23344. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  23345. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  23346. const projectionMatrix = virtualCamera.projectionMatrix;
  23347. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  23348. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  23349. _q.z = -1;
  23350. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  23351. // Calculate the scaled plane vector
  23352. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  23353. const clipBias = 0;
  23354. // Replacing the third row of the projection matrix
  23355. projectionMatrix.elements[ 2 ] = clipPlane.x;
  23356. projectionMatrix.elements[ 6 ] = clipPlane.y;
  23357. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  23358. projectionMatrix.elements[ 14 ] = clipPlane.w;
  23359. //
  23360. this.textureNode.value = renderTarget.texture;
  23361. if ( this.depth === true ) {
  23362. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  23363. }
  23364. material.visible = false;
  23365. const currentRenderTarget = renderer.getRenderTarget();
  23366. const currentMRT = renderer.getMRT();
  23367. const currentAutoClear = renderer.autoClear;
  23368. renderer.setMRT( null );
  23369. renderer.setRenderTarget( renderTarget );
  23370. renderer.autoClear = true;
  23371. if ( needsClear ) {
  23372. renderer.clear();
  23373. this.hasOutput = false;
  23374. } else {
  23375. renderer.render( scene, virtualCamera );
  23376. this.hasOutput = true;
  23377. }
  23378. renderer.setMRT( currentMRT );
  23379. renderer.setRenderTarget( currentRenderTarget );
  23380. renderer.autoClear = currentAutoClear;
  23381. material.visible = true;
  23382. _inReflector = false;
  23383. this.forceUpdate = false;
  23384. }
  23385. }
  23386. /**
  23387. * TSL function for creating a reflector node.
  23388. *
  23389. * @tsl
  23390. * @function
  23391. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23392. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23393. * @param {number} [parameters.resolution=1] - The resolution scale.
  23394. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23395. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23396. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23397. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23398. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23399. * @returns {ReflectorNode}
  23400. */
  23401. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  23402. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  23403. /**
  23404. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  23405. *
  23406. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  23407. *
  23408. * @private
  23409. * @augments BufferGeometry
  23410. */
  23411. class QuadGeometry extends BufferGeometry {
  23412. /**
  23413. * Constructs a new quad geometry.
  23414. *
  23415. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  23416. */
  23417. constructor( flipY = false ) {
  23418. super();
  23419. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  23420. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  23421. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  23422. }
  23423. }
  23424. const _geometry = /*@__PURE__*/ new QuadGeometry();
  23425. /**
  23426. * This module is a helper for passes which need to render a full
  23427. * screen effect which is quite common in context of post processing.
  23428. *
  23429. * The intended usage is to reuse a single quad mesh for rendering
  23430. * subsequent passes by just reassigning the `material` reference.
  23431. *
  23432. * Note: This module can only be used with `WebGPURenderer`.
  23433. *
  23434. * @augments Mesh
  23435. */
  23436. class QuadMesh extends Mesh {
  23437. /**
  23438. * Constructs a new quad mesh.
  23439. *
  23440. * @param {?Material} [material=null] - The material to render the quad mesh with.
  23441. */
  23442. constructor( material = null ) {
  23443. super( _geometry, material );
  23444. /**
  23445. * The camera to render the quad mesh with.
  23446. *
  23447. * @type {OrthographicCamera}
  23448. * @readonly
  23449. */
  23450. this.camera = _camera;
  23451. /**
  23452. * This flag can be used for type testing.
  23453. *
  23454. * @type {boolean}
  23455. * @readonly
  23456. * @default true
  23457. */
  23458. this.isQuadMesh = true;
  23459. }
  23460. /**
  23461. * Async version of `render()`.
  23462. *
  23463. * @async
  23464. * @param {Renderer} renderer - The renderer.
  23465. * @return {Promise} A Promise that resolves when the render has been finished.
  23466. */
  23467. async renderAsync( renderer ) {
  23468. return renderer.renderAsync( this, _camera );
  23469. }
  23470. /**
  23471. * Renders the quad mesh
  23472. *
  23473. * @param {Renderer} renderer - The renderer.
  23474. */
  23475. render( renderer ) {
  23476. renderer.render( this, _camera );
  23477. }
  23478. }
  23479. const _size$1 = /*@__PURE__*/ new Vector2();
  23480. /**
  23481. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  23482. * This module is especially relevant in context of post processing where certain nodes require
  23483. * texture input for their effects. With the helper function `convertToTexture()` which is based
  23484. * on this module, the node system can automatically ensure texture input if required.
  23485. *
  23486. * @augments TextureNode
  23487. */
  23488. class RTTNode extends TextureNode {
  23489. static get type() {
  23490. return 'RTTNode';
  23491. }
  23492. /**
  23493. * Constructs a new RTT node.
  23494. *
  23495. * @param {Node} node - The node to render a texture with.
  23496. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23497. * @param {?number} [height=null] - The height of the internal render target.
  23498. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23499. */
  23500. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  23501. const renderTarget = new RenderTarget( width, height, options );
  23502. super( renderTarget.texture, uv$1() );
  23503. /**
  23504. * This flag can be used for type testing.
  23505. *
  23506. * @type {boolean}
  23507. * @readonly
  23508. * @default true
  23509. */
  23510. this.isRTTNode = true;
  23511. /**
  23512. * The node to render a texture with.
  23513. *
  23514. * @type {Node}
  23515. */
  23516. this.node = node;
  23517. /**
  23518. * The width of the internal render target.
  23519. * If not width is applied, the render target is automatically resized.
  23520. *
  23521. * @type {?number}
  23522. * @default null
  23523. */
  23524. this.width = width;
  23525. /**
  23526. * The height of the internal render target.
  23527. *
  23528. * @type {?number}
  23529. * @default null
  23530. */
  23531. this.height = height;
  23532. /**
  23533. * The pixel ratio
  23534. *
  23535. * @type {number}
  23536. * @default 1
  23537. */
  23538. this.pixelRatio = 1;
  23539. /**
  23540. * The render target
  23541. *
  23542. * @type {RenderTarget}
  23543. */
  23544. this.renderTarget = renderTarget;
  23545. /**
  23546. * Whether the texture requires an update or not.
  23547. *
  23548. * @type {boolean}
  23549. * @default true
  23550. */
  23551. this.textureNeedsUpdate = true;
  23552. /**
  23553. * Whether the texture should automatically be updated or not.
  23554. *
  23555. * @type {boolean}
  23556. * @default true
  23557. */
  23558. this.autoUpdate = true;
  23559. /**
  23560. * The node which is used with the quad mesh for RTT.
  23561. *
  23562. * @private
  23563. * @type {Node}
  23564. * @default null
  23565. */
  23566. this._rttNode = null;
  23567. /**
  23568. * The internal quad mesh for RTT.
  23569. *
  23570. * @private
  23571. * @type {QuadMesh}
  23572. */
  23573. this._quadMesh = new QuadMesh( new NodeMaterial() );
  23574. /**
  23575. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  23576. * the texture once per render in its {@link RTTNode#updateBefore} method.
  23577. *
  23578. * @type {string}
  23579. * @default 'render'
  23580. */
  23581. this.updateBeforeType = NodeUpdateType.RENDER;
  23582. }
  23583. /**
  23584. * Whether the internal render target should automatically be resized or not.
  23585. *
  23586. * @type {boolean}
  23587. * @readonly
  23588. * @default true
  23589. */
  23590. get autoResize() {
  23591. return this.width === null;
  23592. }
  23593. setup( builder ) {
  23594. this._rttNode = this.node.context( builder.getSharedContext() );
  23595. this._quadMesh.material.name = 'RTT';
  23596. this._quadMesh.material.needsUpdate = true;
  23597. return super.setup( builder );
  23598. }
  23599. /**
  23600. * Sets the size of the internal render target
  23601. *
  23602. * @param {number} width - The width to set.
  23603. * @param {number} height - The width to set.
  23604. */
  23605. setSize( width, height ) {
  23606. this.width = width;
  23607. this.height = height;
  23608. const effectiveWidth = width * this.pixelRatio;
  23609. const effectiveHeight = height * this.pixelRatio;
  23610. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23611. this.textureNeedsUpdate = true;
  23612. }
  23613. /**
  23614. * Sets the pixel ratio. This will also resize the render target.
  23615. *
  23616. * @param {number} pixelRatio - The pixel ratio to set.
  23617. */
  23618. setPixelRatio( pixelRatio ) {
  23619. this.pixelRatio = pixelRatio;
  23620. this.setSize( this.width, this.height );
  23621. }
  23622. updateBefore( { renderer } ) {
  23623. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  23624. this.textureNeedsUpdate = false;
  23625. //
  23626. if ( this.autoResize === true ) {
  23627. const pixelRatio = renderer.getPixelRatio();
  23628. const size = renderer.getSize( _size$1 );
  23629. const effectiveWidth = size.width * pixelRatio;
  23630. const effectiveHeight = size.height * pixelRatio;
  23631. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  23632. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23633. this.textureNeedsUpdate = true;
  23634. }
  23635. }
  23636. //
  23637. this._quadMesh.material.fragmentNode = this._rttNode;
  23638. //
  23639. const currentRenderTarget = renderer.getRenderTarget();
  23640. renderer.setRenderTarget( this.renderTarget );
  23641. this._quadMesh.render( renderer );
  23642. renderer.setRenderTarget( currentRenderTarget );
  23643. }
  23644. clone() {
  23645. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  23646. newNode.sampler = this.sampler;
  23647. newNode.referenceNode = this;
  23648. return newNode;
  23649. }
  23650. }
  23651. /**
  23652. * TSL function for creating a RTT node.
  23653. *
  23654. * @tsl
  23655. * @function
  23656. * @param {Node} node - The node to render a texture with.
  23657. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23658. * @param {?number} [height=null] - The height of the internal render target.
  23659. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23660. * @returns {RTTNode}
  23661. */
  23662. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  23663. /**
  23664. * TSL function for converting nodes to textures nodes.
  23665. *
  23666. * @tsl
  23667. * @function
  23668. * @param {Node} node - The node to render a texture with.
  23669. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23670. * @param {?number} [height=null] - The height of the internal render target.
  23671. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23672. * @returns {RTTNode}
  23673. */
  23674. const convertToTexture = ( node, ...params ) => {
  23675. if ( node.isTextureNode ) return node;
  23676. if ( node.isPassNode ) return node.getTextureNode();
  23677. return rtt( node, ...params );
  23678. };
  23679. /**
  23680. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  23681. * depth value and the camera's inverse projection matrix.
  23682. *
  23683. * @tsl
  23684. * @function
  23685. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  23686. * @param {Node<float>} depth - The fragment's depth value.
  23687. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23688. * @return {Node<vec3>} The fragments position in view space.
  23689. */
  23690. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  23691. let clipSpacePosition;
  23692. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  23693. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  23694. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  23695. } else {
  23696. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  23697. }
  23698. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  23699. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  23700. } );
  23701. /**
  23702. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  23703. * and the camera's projection matrix
  23704. *
  23705. * @tsl
  23706. * @function
  23707. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  23708. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  23709. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  23710. */
  23711. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  23712. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  23713. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  23714. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  23715. } );
  23716. /**
  23717. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  23718. * target is available or if flat surface normals are required.
  23719. *
  23720. * @tsl
  23721. * @function
  23722. * @param {Node<vec2>} uv - The texture coordinate.
  23723. * @param {DepthTexture} depthTexture - The depth texture.
  23724. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23725. * @return {Node<vec3>} The computed normal vector.
  23726. */
  23727. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  23728. const size = textureSize( textureLoad( depthTexture ) );
  23729. const p = ivec2( uv.mul( size ) ).toVar();
  23730. const c0 = textureLoad( depthTexture, p ).toVar();
  23731. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  23732. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  23733. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  23734. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  23735. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  23736. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  23737. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  23738. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  23739. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  23740. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  23741. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  23742. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  23743. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  23744. 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 ) ) );
  23745. 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 ) ) );
  23746. return normalize( cross( dpdx, dpdy ) );
  23747. } );
  23748. /**
  23749. * Class representing a node that samples a value using a provided callback function.
  23750. *
  23751. * @extends Node
  23752. */
  23753. class SampleNode extends Node {
  23754. /**
  23755. * Returns the type of the node.
  23756. *
  23757. * @type {string}
  23758. * @readonly
  23759. * @static
  23760. */
  23761. static get type() {
  23762. return 'SampleNode';
  23763. }
  23764. /**
  23765. * Creates an instance of SampleNode.
  23766. *
  23767. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  23768. */
  23769. constructor( callback ) {
  23770. super();
  23771. this.callback = callback;
  23772. /**
  23773. * This flag can be used for type testing.
  23774. *
  23775. * @type {boolean}
  23776. * @readonly
  23777. * @default true
  23778. */
  23779. this.isSampleNode = true;
  23780. }
  23781. /**
  23782. * Sets up the node by sampling with the default UV accessor.
  23783. *
  23784. * @returns {Node} The result of the callback function when called with the UV node.
  23785. */
  23786. setup() {
  23787. return this.sample( uv$1() );
  23788. }
  23789. /**
  23790. * Calls the callback function with the provided UV node.
  23791. *
  23792. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  23793. * @returns {Node} The result of the callback function.
  23794. */
  23795. sample( uv ) {
  23796. return this.callback( uv );
  23797. }
  23798. }
  23799. /**
  23800. * Helper function to create a SampleNode wrapped as a node object.
  23801. *
  23802. * @function
  23803. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  23804. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  23805. */
  23806. const sample = ( callback ) => nodeObject( new SampleNode( callback ) );
  23807. /**
  23808. * EventNode is a node that executes a callback during specific update phases.
  23809. *
  23810. * @augments Node
  23811. */
  23812. class EventNode extends Node {
  23813. static get type() {
  23814. return 'EventNode';
  23815. }
  23816. /**
  23817. * Creates an EventNode.
  23818. *
  23819. * @param {string} eventType - The type of event
  23820. * @param {Function} callback - The callback to execute on update.
  23821. */
  23822. constructor( eventType, callback ) {
  23823. super( 'void' );
  23824. this.eventType = eventType;
  23825. this.callback = callback;
  23826. if ( eventType === EventNode.OBJECT ) {
  23827. this.updateType = NodeUpdateType.OBJECT;
  23828. } else if ( eventType === EventNode.MATERIAL ) {
  23829. this.updateType = NodeUpdateType.RENDER;
  23830. }
  23831. }
  23832. update( frame ) {
  23833. this.callback( frame );
  23834. }
  23835. }
  23836. EventNode.OBJECT = 'object';
  23837. EventNode.MATERIAL = 'material';
  23838. /**
  23839. * Helper to create an EventNode and add it to the stack.
  23840. *
  23841. * @param {string} type - The event type.
  23842. * @param {Function} callback - The callback function.
  23843. * @returns {EventNode}
  23844. */
  23845. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  23846. /**
  23847. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  23848. *
  23849. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  23850. *
  23851. * @param {Function} callback - The callback function.
  23852. * @returns {EventNode}
  23853. */
  23854. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  23855. /**
  23856. * Creates an event that triggers a function when the first object that uses the material is rendered.
  23857. *
  23858. * The event will be bound to the declared TSL function `Fn()`; it must be declared within a `Fn()` or the JS function call must be inherited from one.
  23859. *
  23860. * @param {Function} callback - The callback function.
  23861. * @returns {EventNode}
  23862. */
  23863. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  23864. /**
  23865. * This special type of instanced buffer attribute is intended for compute shaders.
  23866. * In earlier three.js versions it was only possible to update attribute data
  23867. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23868. * new material system and renderer it is now possible to use compute shaders
  23869. * to compute the data for an attribute more efficiently on the GPU.
  23870. *
  23871. * The idea is to create an instance of this class and provide it as an input
  23872. * to {@link StorageBufferNode}.
  23873. *
  23874. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23875. *
  23876. * @augments InstancedBufferAttribute
  23877. */
  23878. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  23879. /**
  23880. * Constructs a new storage instanced buffer attribute.
  23881. *
  23882. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23883. * The subsequent parameters are then obsolete.
  23884. * @param {number} itemSize - The item size.
  23885. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23886. */
  23887. constructor( count, itemSize, typeClass = Float32Array ) {
  23888. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23889. super( array, itemSize );
  23890. /**
  23891. * This flag can be used for type testing.
  23892. *
  23893. * @type {boolean}
  23894. * @readonly
  23895. * @default true
  23896. */
  23897. this.isStorageInstancedBufferAttribute = true;
  23898. }
  23899. }
  23900. /**
  23901. * This special type of buffer attribute is intended for compute shaders.
  23902. * In earlier three.js versions it was only possible to update attribute data
  23903. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23904. * new material system and renderer it is now possible to use compute shaders
  23905. * to compute the data for an attribute more efficiently on the GPU.
  23906. *
  23907. * The idea is to create an instance of this class and provide it as an input
  23908. * to {@link StorageBufferNode}.
  23909. *
  23910. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23911. *
  23912. * @augments BufferAttribute
  23913. */
  23914. class StorageBufferAttribute extends BufferAttribute {
  23915. /**
  23916. * Constructs a new storage buffer attribute.
  23917. *
  23918. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23919. * The subsequent parameters are then obsolete.
  23920. * @param {number} itemSize - The item size.
  23921. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23922. */
  23923. constructor( count, itemSize, typeClass = Float32Array ) {
  23924. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23925. super( array, itemSize );
  23926. /**
  23927. * This flag can be used for type testing.
  23928. *
  23929. * @type {boolean}
  23930. * @readonly
  23931. * @default true
  23932. */
  23933. this.isStorageBufferAttribute = true;
  23934. }
  23935. }
  23936. /**
  23937. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  23938. *
  23939. * @tsl
  23940. * @function
  23941. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23942. * @param {string|Struct} [type='float'] - The data type.
  23943. * @returns {StorageBufferNode}
  23944. */
  23945. const attributeArray = ( count, type = 'float' ) => {
  23946. let itemSize, typedArray;
  23947. if ( type.isStruct === true ) {
  23948. itemSize = type.layout.getLength();
  23949. typedArray = getTypedArrayFromType( 'float' );
  23950. } else {
  23951. itemSize = getLengthFromType( type );
  23952. typedArray = getTypedArrayFromType( type );
  23953. }
  23954. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  23955. const node = storage( buffer, type, count );
  23956. return node;
  23957. };
  23958. /**
  23959. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  23960. *
  23961. * @tsl
  23962. * @function
  23963. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23964. * @param {string|Struct} [type='float'] - The data type.
  23965. * @returns {StorageBufferNode}
  23966. */
  23967. const instancedArray = ( count, type = 'float' ) => {
  23968. let itemSize, typedArray;
  23969. if ( type.isStruct === true ) {
  23970. itemSize = type.layout.getLength();
  23971. typedArray = getTypedArrayFromType( 'float' );
  23972. } else {
  23973. itemSize = getLengthFromType( type );
  23974. typedArray = getTypedArrayFromType( type );
  23975. }
  23976. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  23977. const node = storage( buffer, type, count );
  23978. return node;
  23979. };
  23980. /**
  23981. * A node for representing the uv coordinates of points.
  23982. *
  23983. * Can only be used with a WebGL backend. In WebGPU, point
  23984. * primitives always have the size of one pixel and can thus
  23985. * can't be used as sprite-like objects that display textures.
  23986. *
  23987. * @augments Node
  23988. */
  23989. class PointUVNode extends Node {
  23990. static get type() {
  23991. return 'PointUVNode';
  23992. }
  23993. /**
  23994. * Constructs a new point uv node.
  23995. */
  23996. constructor() {
  23997. super( 'vec2' );
  23998. /**
  23999. * This flag can be used for type testing.
  24000. *
  24001. * @type {boolean}
  24002. * @readonly
  24003. * @default true
  24004. */
  24005. this.isPointUVNode = true;
  24006. }
  24007. generate( /*builder*/ ) {
  24008. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  24009. }
  24010. }
  24011. /**
  24012. * TSL object that represents the uv coordinates of points.
  24013. *
  24014. * @tsl
  24015. * @type {PointUVNode}
  24016. */
  24017. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  24018. const _e1 = /*@__PURE__*/ new Euler();
  24019. const _m1 = /*@__PURE__*/ new Matrix4();
  24020. /**
  24021. * This module allows access to a collection of scene properties. The following predefined TSL objects
  24022. * are available for easier use:
  24023. *
  24024. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  24025. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  24026. * - `backgroundRotation`: A node that represents the scene's background rotation.
  24027. *
  24028. * @augments Node
  24029. */
  24030. class SceneNode extends Node {
  24031. static get type() {
  24032. return 'SceneNode';
  24033. }
  24034. /**
  24035. * Constructs a new scene node.
  24036. *
  24037. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  24038. * @param {?Scene} [scene=null] - A reference to the scene.
  24039. */
  24040. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  24041. super();
  24042. /**
  24043. * The scope defines the type of scene property that is accessed.
  24044. *
  24045. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  24046. */
  24047. this.scope = scope;
  24048. /**
  24049. * A reference to the scene that is going to be accessed.
  24050. *
  24051. * @type {?Scene}
  24052. * @default null
  24053. */
  24054. this.scene = scene;
  24055. }
  24056. /**
  24057. * Depending on the scope, the method returns a different type of node that represents
  24058. * the respective scene property.
  24059. *
  24060. * @param {NodeBuilder} builder - The current node builder.
  24061. * @return {Node} The output node.
  24062. */
  24063. setup( builder ) {
  24064. const scope = this.scope;
  24065. const scene = this.scene !== null ? this.scene : builder.scene;
  24066. let output;
  24067. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  24068. output = reference( 'backgroundBlurriness', 'float', scene );
  24069. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  24070. output = reference( 'backgroundIntensity', 'float', scene );
  24071. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  24072. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24073. const background = scene.background;
  24074. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  24075. _e1.copy( scene.backgroundRotation );
  24076. // accommodate left-handed frame
  24077. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  24078. _m1.makeRotationFromEuler( _e1 );
  24079. } else {
  24080. _m1.identity();
  24081. }
  24082. return _m1;
  24083. } );
  24084. } else {
  24085. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  24086. }
  24087. return output;
  24088. }
  24089. }
  24090. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  24091. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  24092. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  24093. /**
  24094. * TSL object that represents the scene's background blurriness.
  24095. *
  24096. * @tsl
  24097. * @type {SceneNode}
  24098. */
  24099. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  24100. /**
  24101. * TSL object that represents the scene's background intensity.
  24102. *
  24103. * @tsl
  24104. * @type {SceneNode}
  24105. */
  24106. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  24107. /**
  24108. * TSL object that represents the scene's background rotation.
  24109. *
  24110. * @tsl
  24111. * @type {SceneNode}
  24112. */
  24113. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  24114. /**
  24115. * This special version of a texture node can be used to
  24116. * write data into a storage texture with a compute shader.
  24117. *
  24118. * ```js
  24119. * const storageTexture = new THREE.StorageTexture( width, height );
  24120. *
  24121. * const computeTexture = Fn( ( { storageTexture } ) => {
  24122. *
  24123. * const posX = instanceIndex.mod( width );
  24124. * const posY = instanceIndex.div( width );
  24125. * const indexUV = uvec2( posX, posY );
  24126. *
  24127. * // generate RGB values
  24128. *
  24129. * const r = 1;
  24130. * const g = 1;
  24131. * const b = 1;
  24132. *
  24133. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  24134. *
  24135. * } );
  24136. *
  24137. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  24138. * renderer.computeAsync( computeNode );
  24139. * ```
  24140. *
  24141. * This node can only be used with a WebGPU backend.
  24142. *
  24143. * @augments TextureNode
  24144. */
  24145. class StorageTextureNode extends TextureNode {
  24146. static get type() {
  24147. return 'StorageTextureNode';
  24148. }
  24149. /**
  24150. * Constructs a new storage texture node.
  24151. *
  24152. * @param {StorageTexture} value - The storage texture.
  24153. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24154. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24155. */
  24156. constructor( value, uvNode, storeNode = null ) {
  24157. super( value, uvNode );
  24158. /**
  24159. * The value node that should be stored in the texture.
  24160. *
  24161. * @type {?Node}
  24162. * @default null
  24163. */
  24164. this.storeNode = storeNode;
  24165. /**
  24166. * This flag can be used for type testing.
  24167. *
  24168. * @type {boolean}
  24169. * @readonly
  24170. * @default true
  24171. */
  24172. this.isStorageTextureNode = true;
  24173. /**
  24174. * The access type of the texture node.
  24175. *
  24176. * @type {string}
  24177. * @default 'writeOnly'
  24178. */
  24179. this.access = NodeAccess.WRITE_ONLY;
  24180. }
  24181. /**
  24182. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  24183. *
  24184. * @param {NodeBuilder} builder - The current node builder.
  24185. * @return {string} The input type.
  24186. */
  24187. getInputType( /*builder*/ ) {
  24188. return 'storageTexture';
  24189. }
  24190. setup( builder ) {
  24191. super.setup( builder );
  24192. const properties = builder.getNodeProperties( this );
  24193. properties.storeNode = this.storeNode;
  24194. return properties;
  24195. }
  24196. /**
  24197. * Defines the node access.
  24198. *
  24199. * @param {string} value - The node access.
  24200. * @return {StorageTextureNode} A reference to this node.
  24201. */
  24202. setAccess( value ) {
  24203. this.access = value;
  24204. return this;
  24205. }
  24206. /**
  24207. * Generates the code snippet of the storage node. If no `storeNode`
  24208. * is defined, the texture node is generated as normal texture.
  24209. *
  24210. * @param {NodeBuilder} builder - The current node builder.
  24211. * @param {string} output - The current output.
  24212. * @return {string} The generated code snippet.
  24213. */
  24214. generate( builder, output ) {
  24215. let snippet;
  24216. if ( this.storeNode !== null ) {
  24217. snippet = this.generateStore( builder );
  24218. } else {
  24219. snippet = super.generate( builder, output );
  24220. }
  24221. return snippet;
  24222. }
  24223. /**
  24224. * Convenience method for configuring a read/write node access.
  24225. *
  24226. * @return {StorageTextureNode} A reference to this node.
  24227. */
  24228. toReadWrite() {
  24229. return this.setAccess( NodeAccess.READ_WRITE );
  24230. }
  24231. /**
  24232. * Convenience method for configuring a read-only node access.
  24233. *
  24234. * @return {StorageTextureNode} A reference to this node.
  24235. */
  24236. toReadOnly() {
  24237. return this.setAccess( NodeAccess.READ_ONLY );
  24238. }
  24239. /**
  24240. * Convenience method for configuring a write-only node access.
  24241. *
  24242. * @return {StorageTextureNode} A reference to this node.
  24243. */
  24244. toWriteOnly() {
  24245. return this.setAccess( NodeAccess.WRITE_ONLY );
  24246. }
  24247. /**
  24248. * Generates the code snippet of the storage texture node.
  24249. *
  24250. * @param {NodeBuilder} builder - The current node builder.
  24251. */
  24252. generateStore( builder ) {
  24253. const properties = builder.getNodeProperties( this );
  24254. const { uvNode, storeNode, depthNode } = properties;
  24255. const textureProperty = super.generate( builder, 'property' );
  24256. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  24257. const storeSnippet = storeNode.build( builder, 'vec4' );
  24258. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24259. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  24260. builder.addLineFlowCode( snippet, this );
  24261. }
  24262. clone() {
  24263. const newNode = super.clone();
  24264. newNode.storeNode = this.storeNode;
  24265. return newNode;
  24266. }
  24267. }
  24268. /**
  24269. * TSL function for creating a storage texture node.
  24270. *
  24271. * @tsl
  24272. * @function
  24273. * @param {StorageTexture} value - The storage texture.
  24274. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  24275. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24276. * @returns {StorageTextureNode}
  24277. */
  24278. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  24279. /**
  24280. * TODO: Explain difference to `storageTexture()`.
  24281. *
  24282. * @tsl
  24283. * @function
  24284. * @param {StorageTexture} value - The storage texture.
  24285. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24286. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24287. * @returns {StorageTextureNode}
  24288. */
  24289. const textureStore = ( value, uvNode, storeNode ) => {
  24290. const node = storageTexture( value, uvNode, storeNode );
  24291. if ( storeNode !== null ) node.toStack();
  24292. return node;
  24293. };
  24294. const normal = Fn( ( { texture, uv } ) => {
  24295. const epsilon = 0.0001;
  24296. const ret = vec3().toVar();
  24297. If( uv.x.lessThan( epsilon ), () => {
  24298. ret.assign( vec3( 1, 0, 0 ) );
  24299. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  24300. ret.assign( vec3( 0, 1, 0 ) );
  24301. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  24302. ret.assign( vec3( 0, 0, 1 ) );
  24303. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  24304. ret.assign( vec3( -1, 0, 0 ) );
  24305. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  24306. ret.assign( vec3( 0, -1, 0 ) );
  24307. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  24308. ret.assign( vec3( 0, 0, -1 ) );
  24309. } ).Else( () => {
  24310. const step = 0.01;
  24311. 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 );
  24312. 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 );
  24313. 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 );
  24314. ret.assign( vec3( x, y, z ) );
  24315. } );
  24316. return ret.normalize();
  24317. } );
  24318. /**
  24319. * This type of uniform node represents a 3D texture.
  24320. *
  24321. * @augments TextureNode
  24322. */
  24323. class Texture3DNode extends TextureNode {
  24324. static get type() {
  24325. return 'Texture3DNode';
  24326. }
  24327. /**
  24328. * Constructs a new 3D texture node.
  24329. *
  24330. * @param {Data3DTexture} value - The 3D texture.
  24331. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24332. * @param {?Node<int>} [levelNode=null] - The level node.
  24333. */
  24334. constructor( value, uvNode = null, levelNode = null ) {
  24335. super( value, uvNode, levelNode );
  24336. /**
  24337. * This flag can be used for type testing.
  24338. *
  24339. * @type {boolean}
  24340. * @readonly
  24341. * @default true
  24342. */
  24343. this.isTexture3DNode = true;
  24344. }
  24345. /**
  24346. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  24347. *
  24348. * @param {NodeBuilder} builder - The current node builder.
  24349. * @return {string} The input type.
  24350. */
  24351. getInputType( /*builder*/ ) {
  24352. return 'texture3D';
  24353. }
  24354. /**
  24355. * Returns a default uv node which is in context of 3D textures a three-dimensional
  24356. * uv node.
  24357. *
  24358. * @return {Node<vec3>} The default uv node.
  24359. */
  24360. getDefaultUV() {
  24361. return vec3( 0.5, 0.5, 0.5 );
  24362. }
  24363. /**
  24364. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  24365. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  24366. *
  24367. * @param {boolean} value - The update toggle.
  24368. */
  24369. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  24370. /**
  24371. * Overwrites the default implementation to return the unmodified uv node.
  24372. *
  24373. * @param {NodeBuilder} builder - The current node builder.
  24374. * @param {Node} uvNode - The uv node to setup.
  24375. * @return {Node} The unmodified uv node.
  24376. */
  24377. setupUV( builder, uvNode ) {
  24378. const texture = this.value;
  24379. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  24380. if ( this.sampler ) {
  24381. uvNode = uvNode.flipY();
  24382. } else {
  24383. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24384. }
  24385. }
  24386. return uvNode;
  24387. }
  24388. /**
  24389. * Generates the uv code snippet.
  24390. *
  24391. * @param {NodeBuilder} builder - The current node builder.
  24392. * @param {Node} uvNode - The uv node to generate code for.
  24393. * @return {string} The generated code snippet.
  24394. */
  24395. generateUV( builder, uvNode ) {
  24396. return uvNode.build( builder, 'vec3' );
  24397. }
  24398. /**
  24399. * TODO.
  24400. *
  24401. * @param {Node<vec3>} uvNode - The uv node .
  24402. * @return {Node<vec3>} TODO.
  24403. */
  24404. normal( uvNode ) {
  24405. return normal( { texture: this, uv: uvNode } );
  24406. }
  24407. }
  24408. /**
  24409. * TSL function for creating a 3D texture node.
  24410. *
  24411. * @tsl
  24412. * @function
  24413. * @param {Data3DTexture} value - The 3D texture.
  24414. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24415. * @param {?Node<int>} [levelNode=null] - The level node.
  24416. * @returns {Texture3DNode}
  24417. */
  24418. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  24419. /**
  24420. * A special type of reference node that allows to link values in
  24421. * `userData` fields to node objects.
  24422. * ```js
  24423. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  24424. *
  24425. * const material = new THREE.SpriteNodeMaterial();
  24426. * material.rotationNode = userData( 'rotation', 'float' );
  24427. * ```
  24428. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  24429. * will automatically be updated when the `rotation` user data field changes.
  24430. *
  24431. * @augments ReferenceNode
  24432. */
  24433. class UserDataNode extends ReferenceNode {
  24434. static get type() {
  24435. return 'UserDataNode';
  24436. }
  24437. /**
  24438. * Constructs a new user data node.
  24439. *
  24440. * @param {string} property - The property name that should be referenced by the node.
  24441. * @param {string} inputType - The node data type of the reference.
  24442. * @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.
  24443. */
  24444. constructor( property, inputType, userData = null ) {
  24445. super( property, inputType, userData );
  24446. /**
  24447. * A reference to the `userData` object. If not provided, the `userData`
  24448. * property of the 3D object that uses the node material is evaluated.
  24449. *
  24450. * @type {?Object}
  24451. * @default null
  24452. */
  24453. this.userData = userData;
  24454. }
  24455. /**
  24456. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  24457. * `userData` field.
  24458. *
  24459. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  24460. * @return {Object} A reference to the `userData` field.
  24461. */
  24462. updateReference( state ) {
  24463. this.reference = this.userData !== null ? this.userData : state.object.userData;
  24464. return this.reference;
  24465. }
  24466. }
  24467. /**
  24468. * TSL function for creating a user data node.
  24469. *
  24470. * @tsl
  24471. * @function
  24472. * @param {string} name - The property name that should be referenced by the node.
  24473. * @param {string} inputType - The node data type of the reference.
  24474. * @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.
  24475. * @returns {UserDataNode}
  24476. */
  24477. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  24478. const _objectData = new WeakMap();
  24479. /**
  24480. * A node for representing motion or velocity vectors. Foundation
  24481. * for advanced post processing effects like motion blur or TRAA.
  24482. *
  24483. * The node keeps track of the model, view and projection matrices
  24484. * of the previous frame and uses them to compute offsets in NDC space.
  24485. * These offsets represent the final velocity.
  24486. *
  24487. * @augments TempNode
  24488. */
  24489. class VelocityNode extends TempNode {
  24490. static get type() {
  24491. return 'VelocityNode';
  24492. }
  24493. /**
  24494. * Constructs a new vertex color node.
  24495. */
  24496. constructor() {
  24497. super( 'vec2' );
  24498. /**
  24499. * The current projection matrix.
  24500. *
  24501. * @type {?Matrix4}
  24502. * @default null
  24503. */
  24504. this.projectionMatrix = null;
  24505. /**
  24506. * Overwritten since velocity nodes are updated per object.
  24507. *
  24508. * @type {string}
  24509. * @default 'object'
  24510. */
  24511. this.updateType = NodeUpdateType.OBJECT;
  24512. /**
  24513. * Overwritten since velocity nodes save data after the update.
  24514. *
  24515. * @type {string}
  24516. * @default 'object'
  24517. */
  24518. this.updateAfterType = NodeUpdateType.OBJECT;
  24519. /**
  24520. * Uniform node representing the previous model matrix in world space.
  24521. *
  24522. * @type {UniformNode<mat4>}
  24523. * @default null
  24524. */
  24525. this.previousModelWorldMatrix = uniform( new Matrix4() );
  24526. /**
  24527. * Uniform node representing the previous projection matrix.
  24528. *
  24529. * @type {UniformNode<mat4>}
  24530. * @default null
  24531. */
  24532. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  24533. /**
  24534. * Uniform node representing the previous view matrix.
  24535. *
  24536. * @type {UniformNode<mat4>}
  24537. * @default null
  24538. */
  24539. this.previousCameraViewMatrix = uniform( new Matrix4() );
  24540. }
  24541. /**
  24542. * Sets the given projection matrix.
  24543. *
  24544. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  24545. */
  24546. setProjectionMatrix( projectionMatrix ) {
  24547. this.projectionMatrix = projectionMatrix;
  24548. }
  24549. /**
  24550. * Updates velocity specific uniforms.
  24551. *
  24552. * @param {NodeFrame} frame - A reference to the current node frame.
  24553. */
  24554. update( { frameId, camera, object } ) {
  24555. const previousModelMatrix = getPreviousMatrix( object );
  24556. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  24557. //
  24558. const cameraData = getData( camera );
  24559. if ( cameraData.frameId !== frameId ) {
  24560. cameraData.frameId = frameId;
  24561. if ( cameraData.previousProjectionMatrix === undefined ) {
  24562. cameraData.previousProjectionMatrix = new Matrix4();
  24563. cameraData.previousCameraViewMatrix = new Matrix4();
  24564. cameraData.currentProjectionMatrix = new Matrix4();
  24565. cameraData.currentCameraViewMatrix = new Matrix4();
  24566. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24567. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  24568. } else {
  24569. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  24570. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  24571. }
  24572. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24573. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  24574. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  24575. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  24576. }
  24577. }
  24578. /**
  24579. * Overwritten to updated velocity specific uniforms.
  24580. *
  24581. * @param {NodeFrame} frame - A reference to the current node frame.
  24582. */
  24583. updateAfter( { object } ) {
  24584. getPreviousMatrix( object ).copy( object.matrixWorld );
  24585. }
  24586. /**
  24587. * Implements the velocity computation based on the previous and current vertex data.
  24588. *
  24589. * @param {NodeBuilder} builder - A reference to the current node builder.
  24590. * @return {Node<vec2>} The motion vector.
  24591. */
  24592. setup( /*builder*/ ) {
  24593. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  24594. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  24595. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24596. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  24597. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  24598. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  24599. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  24600. return velocity;
  24601. }
  24602. }
  24603. function getData( object ) {
  24604. let objectData = _objectData.get( object );
  24605. if ( objectData === undefined ) {
  24606. objectData = {};
  24607. _objectData.set( object, objectData );
  24608. }
  24609. return objectData;
  24610. }
  24611. function getPreviousMatrix( object, index = 0 ) {
  24612. const objectData = getData( object );
  24613. let matrix = objectData[ index ];
  24614. if ( matrix === undefined ) {
  24615. objectData[ index ] = matrix = new Matrix4();
  24616. objectData[ index ].copy( object.matrixWorld );
  24617. }
  24618. return matrix;
  24619. }
  24620. /**
  24621. * TSL object that represents the velocity of a render pass.
  24622. *
  24623. * @tsl
  24624. * @type {VelocityNode}
  24625. */
  24626. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  24627. /**
  24628. * Computes a grayscale value for the given RGB color value.
  24629. *
  24630. * @tsl
  24631. * @function
  24632. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  24633. * @return {Node<vec3>} The grayscale color.
  24634. */
  24635. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24636. return luminance( color.rgb );
  24637. } );
  24638. /**
  24639. * Super-saturates or desaturates the given RGB color.
  24640. *
  24641. * @tsl
  24642. * @function
  24643. * @param {Node<vec3>} color - The input color.
  24644. * @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.
  24645. * @return {Node<vec3>} The saturated color.
  24646. */
  24647. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24648. return adjustment.mix( luminance( color.rgb ), color.rgb );
  24649. } );
  24650. /**
  24651. * Selectively enhance the intensity of less saturated RGB colors. Can result
  24652. * in a more natural and visually appealing image with enhanced color depth
  24653. * compared to {@link ColorAdjustment#saturation}.
  24654. *
  24655. * @tsl
  24656. * @function
  24657. * @param {Node<vec3>} color - The input color.
  24658. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  24659. * @return {Node<vec3>} The updated color.
  24660. */
  24661. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24662. const average = add( color.r, color.g, color.b ).div( 3.0 );
  24663. const mx = color.r.max( color.g.max( color.b ) );
  24664. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  24665. return mix( color.rgb, mx, amt );
  24666. } );
  24667. /**
  24668. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  24669. *
  24670. * @tsl
  24671. * @function
  24672. * @param {Node<vec3>} color - The input color.
  24673. * @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.
  24674. * @return {Node<vec3>} The updated color.
  24675. */
  24676. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24677. const k = vec3( 0.57735, 0.57735, 0.57735 );
  24678. const cosAngle = adjustment.cos();
  24679. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  24680. } );
  24681. /**
  24682. * Computes the luminance for the given RGB color value.
  24683. *
  24684. * @tsl
  24685. * @function
  24686. * @param {Node<vec3>} color - The color value to compute the luminance for.
  24687. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  24688. * @return {Node<vec3>} The luminance.
  24689. */
  24690. const luminance = (
  24691. color,
  24692. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  24693. ) => dot( color, luminanceCoefficients );
  24694. /**
  24695. * Color Decision List (CDL) v1.2
  24696. *
  24697. * Compact representation of color grading information, defined by slope, offset, power, and
  24698. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  24699. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  24700. *
  24701. * @tsl
  24702. * @function
  24703. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  24704. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  24705. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  24706. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  24707. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  24708. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  24709. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  24710. *
  24711. * References:
  24712. * - ASC CDL v1.2
  24713. * - {@link https://blender.stackexchange.com/a/55239/43930}
  24714. * - {@link https://docs.acescentral.com/specifications/acescc/}
  24715. */
  24716. const cdl = /*@__PURE__*/ Fn( ( [
  24717. color,
  24718. slope = vec3( 1 ),
  24719. offset = vec3( 0 ),
  24720. power = vec3( 1 ),
  24721. saturation = float( 1 ),
  24722. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  24723. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  24724. ] ) => {
  24725. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  24726. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  24727. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  24728. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  24729. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  24730. const pv = v.pow( power ).toVar();
  24731. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  24732. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  24733. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  24734. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  24735. return vec4( v.rgb, color.a );
  24736. } );
  24737. /**
  24738. * Represents a posterize effect which reduces the number of colors
  24739. * in an image, resulting in a more blocky and stylized appearance.
  24740. *
  24741. * @augments TempNode
  24742. */
  24743. class PosterizeNode extends TempNode {
  24744. static get type() {
  24745. return 'PosterizeNode';
  24746. }
  24747. /**
  24748. * Constructs a new posterize node.
  24749. *
  24750. * @param {Node} sourceNode - The input color.
  24751. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24752. */
  24753. constructor( sourceNode, stepsNode ) {
  24754. super();
  24755. /**
  24756. * The input color.
  24757. *
  24758. * @type {Node}
  24759. */
  24760. this.sourceNode = sourceNode;
  24761. /**
  24762. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24763. *
  24764. * @type {Node}
  24765. */
  24766. this.stepsNode = stepsNode;
  24767. }
  24768. setup() {
  24769. const { sourceNode, stepsNode } = this;
  24770. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  24771. }
  24772. }
  24773. /**
  24774. * TSL function for creating a posterize node.
  24775. *
  24776. * @tsl
  24777. * @function
  24778. * @param {Node} sourceNode - The input color.
  24779. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24780. * @returns {PosterizeNode}
  24781. */
  24782. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  24783. const _size = /*@__PURE__*/ new Vector2();
  24784. /**
  24785. * Represents the texture of a pass node.
  24786. *
  24787. * @augments TextureNode
  24788. */
  24789. class PassTextureNode extends TextureNode {
  24790. static get type() {
  24791. return 'PassTextureNode';
  24792. }
  24793. /**
  24794. * Constructs a new pass texture node.
  24795. *
  24796. * @param {PassNode} passNode - The pass node.
  24797. * @param {Texture} texture - The output texture.
  24798. */
  24799. constructor( passNode, texture ) {
  24800. super( texture );
  24801. /**
  24802. * A reference to the pass node.
  24803. *
  24804. * @type {PassNode}
  24805. */
  24806. this.passNode = passNode;
  24807. this.setUpdateMatrix( false );
  24808. }
  24809. setup( builder ) {
  24810. this.passNode.build( builder );
  24811. return super.setup( builder );
  24812. }
  24813. clone() {
  24814. return new this.constructor( this.passNode, this.value );
  24815. }
  24816. }
  24817. /**
  24818. * An extension of `PassTextureNode` which allows to manage more than one
  24819. * internal texture. Relevant for the `getPreviousTexture()` related API.
  24820. *
  24821. * @augments PassTextureNode
  24822. */
  24823. class PassMultipleTextureNode extends PassTextureNode {
  24824. static get type() {
  24825. return 'PassMultipleTextureNode';
  24826. }
  24827. /**
  24828. * Constructs a new pass texture node.
  24829. *
  24830. * @param {PassNode} passNode - The pass node.
  24831. * @param {string} textureName - The output texture name.
  24832. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  24833. */
  24834. constructor( passNode, textureName, previousTexture = false ) {
  24835. // null is passed to the super call since this class does not
  24836. // use an external texture for rendering pass data into. Instead
  24837. // the texture is managed by the pass node itself
  24838. super( passNode, null );
  24839. /**
  24840. * The output texture name.
  24841. *
  24842. * @type {string}
  24843. */
  24844. this.textureName = textureName;
  24845. /**
  24846. * Whether previous frame data should be used or not.
  24847. *
  24848. * @type {boolean}
  24849. */
  24850. this.previousTexture = previousTexture;
  24851. }
  24852. /**
  24853. * Updates the texture reference of this node.
  24854. */
  24855. updateTexture() {
  24856. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  24857. }
  24858. setup( builder ) {
  24859. this.updateTexture();
  24860. return super.setup( builder );
  24861. }
  24862. clone() {
  24863. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  24864. newNode.uvNode = this.uvNode;
  24865. newNode.levelNode = this.levelNode;
  24866. newNode.biasNode = this.biasNode;
  24867. newNode.sampler = this.sampler;
  24868. newNode.depthNode = this.depthNode;
  24869. newNode.compareNode = this.compareNode;
  24870. newNode.gradNode = this.gradNode;
  24871. return newNode;
  24872. }
  24873. }
  24874. /**
  24875. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  24876. * This pass produces a render for the given scene and camera and can provide multiple outputs
  24877. * via MRT for further processing.
  24878. *
  24879. * ```js
  24880. * const postProcessing = new PostProcessing( renderer );
  24881. *
  24882. * const scenePass = pass( scene, camera );
  24883. *
  24884. * postProcessing.outputNode = scenePass;
  24885. * ```
  24886. *
  24887. * @augments TempNode
  24888. */
  24889. class PassNode extends TempNode {
  24890. static get type() {
  24891. return 'PassNode';
  24892. }
  24893. /**
  24894. * Constructs a new pass node.
  24895. *
  24896. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  24897. * @param {Scene} scene - A reference to the scene.
  24898. * @param {Camera} camera - A reference to the camera.
  24899. * @param {Object} options - Options for the internal render target.
  24900. */
  24901. constructor( scope, scene, camera, options = {} ) {
  24902. super( 'vec4' );
  24903. /**
  24904. * The scope of the pass. The scope determines whether the node outputs color or depth.
  24905. *
  24906. * @type {('color'|'depth')}
  24907. */
  24908. this.scope = scope;
  24909. /**
  24910. * A reference to the scene.
  24911. *
  24912. * @type {Scene}
  24913. */
  24914. this.scene = scene;
  24915. /**
  24916. * A reference to the camera.
  24917. *
  24918. * @type {Camera}
  24919. */
  24920. this.camera = camera;
  24921. /**
  24922. * Options for the internal render target.
  24923. *
  24924. * @type {Object}
  24925. */
  24926. this.options = options;
  24927. /**
  24928. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  24929. *
  24930. * @private
  24931. * @type {number}
  24932. * @default 1
  24933. */
  24934. this._pixelRatio = 1;
  24935. /**
  24936. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  24937. * @private
  24938. * @type {number}
  24939. * @default 1
  24940. */
  24941. this._width = 1;
  24942. /**
  24943. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  24944. * @private
  24945. * @type {number}
  24946. * @default 1
  24947. */
  24948. this._height = 1;
  24949. const depthTexture = new DepthTexture();
  24950. depthTexture.isRenderTargetTexture = true;
  24951. //depthTexture.type = FloatType;
  24952. depthTexture.name = 'depth';
  24953. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  24954. renderTarget.texture.name = 'output';
  24955. renderTarget.depthTexture = depthTexture;
  24956. /**
  24957. * The pass's render target.
  24958. *
  24959. * @type {RenderTarget}
  24960. */
  24961. this.renderTarget = renderTarget;
  24962. /**
  24963. * A dictionary holding the internal result textures.
  24964. *
  24965. * @private
  24966. * @type {Object<string, Texture>}
  24967. */
  24968. this._textures = {
  24969. output: renderTarget.texture,
  24970. depth: depthTexture
  24971. };
  24972. /**
  24973. * A dictionary holding the internal texture nodes.
  24974. *
  24975. * @private
  24976. * @type {Object<string, TextureNode>}
  24977. */
  24978. this._textureNodes = {};
  24979. /**
  24980. * A dictionary holding the internal depth nodes.
  24981. *
  24982. * @private
  24983. * @type {Object}
  24984. */
  24985. this._linearDepthNodes = {};
  24986. /**
  24987. * A dictionary holding the internal viewZ nodes.
  24988. *
  24989. * @private
  24990. * @type {Object}
  24991. */
  24992. this._viewZNodes = {};
  24993. /**
  24994. * A dictionary holding the texture data of the previous frame.
  24995. * Used for computing velocity/motion vectors.
  24996. *
  24997. * @private
  24998. * @type {Object<string, Texture>}
  24999. */
  25000. this._previousTextures = {};
  25001. /**
  25002. * A dictionary holding the texture nodes of the previous frame.
  25003. * Used for computing velocity/motion vectors.
  25004. *
  25005. * @private
  25006. * @type {Object<string, TextureNode>}
  25007. */
  25008. this._previousTextureNodes = {};
  25009. /**
  25010. * The `near` property of the camera as a uniform.
  25011. *
  25012. * @private
  25013. * @type {UniformNode}
  25014. */
  25015. this._cameraNear = uniform( 0 );
  25016. /**
  25017. * The `far` property of the camera as a uniform.
  25018. *
  25019. * @private
  25020. * @type {UniformNode}
  25021. */
  25022. this._cameraFar = uniform( 0 );
  25023. /**
  25024. * A MRT node configuring the MRT settings.
  25025. *
  25026. * @private
  25027. * @type {?MRTNode}
  25028. * @default null
  25029. */
  25030. this._mrt = null;
  25031. /**
  25032. * Layer object for configuring the camera that is used
  25033. * to produce the pass.
  25034. *
  25035. * @private
  25036. * @type {?Layers}
  25037. * @default null
  25038. */
  25039. this._layers = null;
  25040. /**
  25041. * Scales the resolution of the internal render target.
  25042. *
  25043. * @private
  25044. * @type {number}
  25045. * @default 1
  25046. */
  25047. this._resolution = 1;
  25048. /**
  25049. * Custom viewport definition.
  25050. *
  25051. * @private
  25052. * @type {?Vector4}
  25053. * @default null
  25054. */
  25055. this._viewport = null;
  25056. /**
  25057. * Custom scissor definition.
  25058. *
  25059. * @private
  25060. * @type {?Vector4}
  25061. * @default null
  25062. */
  25063. this._scissor = null;
  25064. /**
  25065. * This flag can be used for type testing.
  25066. *
  25067. * @type {boolean}
  25068. * @readonly
  25069. * @default true
  25070. */
  25071. this.isPassNode = true;
  25072. /**
  25073. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  25074. * scene once per frame in its {@link PassNode#updateBefore} method.
  25075. *
  25076. * @type {string}
  25077. * @default 'frame'
  25078. */
  25079. this.updateBeforeType = NodeUpdateType.FRAME;
  25080. /**
  25081. * This flag is used for global cache.
  25082. *
  25083. * @type {boolean}
  25084. * @default true
  25085. */
  25086. this.global = true;
  25087. }
  25088. /**
  25089. * Sets the resolution for the pass.
  25090. * The resolution is a factor that is multiplied with the renderer's width and height.
  25091. *
  25092. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  25093. * @return {PassNode} A reference to this pass.
  25094. */
  25095. setResolution( resolution ) {
  25096. this._resolution = resolution;
  25097. return this;
  25098. }
  25099. /**
  25100. * Gets the current resolution of the pass.
  25101. *
  25102. * @return {number} The current resolution. A value of `1` means full resolution.
  25103. */
  25104. getResolution() {
  25105. return this._resolution;
  25106. }
  25107. /**
  25108. * Sets the layer configuration that should be used when rendering the pass.
  25109. *
  25110. * @param {Layers} layers - The layers object to set.
  25111. * @return {PassNode} A reference to this pass.
  25112. */
  25113. setLayers( layers ) {
  25114. this._layers = layers;
  25115. return this;
  25116. }
  25117. /**
  25118. * Gets the current layer configuration of the pass.
  25119. *
  25120. * @return {?Layers} .
  25121. */
  25122. getLayers() {
  25123. return this._layers;
  25124. }
  25125. /**
  25126. * Sets the given MRT node to setup MRT for this pass.
  25127. *
  25128. * @param {MRTNode} mrt - The MRT object.
  25129. * @return {PassNode} A reference to this pass.
  25130. */
  25131. setMRT( mrt ) {
  25132. this._mrt = mrt;
  25133. return this;
  25134. }
  25135. /**
  25136. * Returns the current MRT node.
  25137. *
  25138. * @return {MRTNode} The current MRT node.
  25139. */
  25140. getMRT() {
  25141. return this._mrt;
  25142. }
  25143. /**
  25144. * Returns the texture for the given output name.
  25145. *
  25146. * @param {string} name - The output name to get the texture for.
  25147. * @return {Texture} The texture.
  25148. */
  25149. getTexture( name ) {
  25150. let texture = this._textures[ name ];
  25151. if ( texture === undefined ) {
  25152. const refTexture = this.renderTarget.texture;
  25153. texture = refTexture.clone();
  25154. texture.name = name;
  25155. this._textures[ name ] = texture;
  25156. this.renderTarget.textures.push( texture );
  25157. }
  25158. return texture;
  25159. }
  25160. /**
  25161. * Returns the texture holding the data of the previous frame for the given output name.
  25162. *
  25163. * @param {string} name - The output name to get the texture for.
  25164. * @return {Texture} The texture holding the data of the previous frame.
  25165. */
  25166. getPreviousTexture( name ) {
  25167. let texture = this._previousTextures[ name ];
  25168. if ( texture === undefined ) {
  25169. texture = this.getTexture( name ).clone();
  25170. this._previousTextures[ name ] = texture;
  25171. }
  25172. return texture;
  25173. }
  25174. /**
  25175. * Switches current and previous textures for the given output name.
  25176. *
  25177. * @param {string} name - The output name.
  25178. */
  25179. toggleTexture( name ) {
  25180. const prevTexture = this._previousTextures[ name ];
  25181. if ( prevTexture !== undefined ) {
  25182. const texture = this._textures[ name ];
  25183. const index = this.renderTarget.textures.indexOf( texture );
  25184. this.renderTarget.textures[ index ] = prevTexture;
  25185. this._textures[ name ] = prevTexture;
  25186. this._previousTextures[ name ] = texture;
  25187. this._textureNodes[ name ].updateTexture();
  25188. this._previousTextureNodes[ name ].updateTexture();
  25189. }
  25190. }
  25191. /**
  25192. * Returns the texture node for the given output name.
  25193. *
  25194. * @param {string} [name='output'] - The output name to get the texture node for.
  25195. * @return {TextureNode} The texture node.
  25196. */
  25197. getTextureNode( name = 'output' ) {
  25198. let textureNode = this._textureNodes[ name ];
  25199. if ( textureNode === undefined ) {
  25200. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  25201. textureNode.updateTexture();
  25202. this._textureNodes[ name ] = textureNode;
  25203. }
  25204. return textureNode;
  25205. }
  25206. /**
  25207. * Returns the previous texture node for the given output name.
  25208. *
  25209. * @param {string} [name='output'] - The output name to get the previous texture node for.
  25210. * @return {TextureNode} The previous texture node.
  25211. */
  25212. getPreviousTextureNode( name = 'output' ) {
  25213. let textureNode = this._previousTextureNodes[ name ];
  25214. if ( textureNode === undefined ) {
  25215. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  25216. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  25217. textureNode.updateTexture();
  25218. this._previousTextureNodes[ name ] = textureNode;
  25219. }
  25220. return textureNode;
  25221. }
  25222. /**
  25223. * Returns a viewZ node of this pass.
  25224. *
  25225. * @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.
  25226. * @return {Node} The viewZ node.
  25227. */
  25228. getViewZNode( name = 'depth' ) {
  25229. let viewZNode = this._viewZNodes[ name ];
  25230. if ( viewZNode === undefined ) {
  25231. const cameraNear = this._cameraNear;
  25232. const cameraFar = this._cameraFar;
  25233. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  25234. }
  25235. return viewZNode;
  25236. }
  25237. /**
  25238. * Returns a linear depth node of this pass.
  25239. *
  25240. * @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.
  25241. * @return {Node} The linear depth node.
  25242. */
  25243. getLinearDepthNode( name = 'depth' ) {
  25244. let linearDepthNode = this._linearDepthNodes[ name ];
  25245. if ( linearDepthNode === undefined ) {
  25246. const cameraNear = this._cameraNear;
  25247. const cameraFar = this._cameraFar;
  25248. const viewZNode = this.getViewZNode( name );
  25249. // TODO: just if ( builder.camera.isPerspectiveCamera )
  25250. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  25251. }
  25252. return linearDepthNode;
  25253. }
  25254. /**
  25255. * Precompiles the pass.
  25256. *
  25257. * Note that this method must be called after the pass configuartion is complete.
  25258. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  25259. *
  25260. * @async
  25261. * @param {Renderer} renderer - The renderer.
  25262. * @return {Promise} A Promise that resolves when the compile has been finished.
  25263. * @see {@link Renderer#compileAsync}
  25264. */
  25265. async compileAsync( renderer ) {
  25266. const currentRenderTarget = renderer.getRenderTarget();
  25267. const currentMRT = renderer.getMRT();
  25268. renderer.setRenderTarget( this.renderTarget );
  25269. renderer.setMRT( this._mrt );
  25270. await renderer.compileAsync( this.scene, this.camera );
  25271. renderer.setRenderTarget( currentRenderTarget );
  25272. renderer.setMRT( currentMRT );
  25273. }
  25274. setup( { renderer } ) {
  25275. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  25276. this.renderTarget.texture.type = renderer.getColorBufferType();
  25277. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  25278. }
  25279. updateBefore( frame ) {
  25280. const { renderer } = frame;
  25281. const { scene } = this;
  25282. let camera;
  25283. let pixelRatio;
  25284. const outputRenderTarget = renderer.getOutputRenderTarget();
  25285. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  25286. pixelRatio = 1;
  25287. camera = renderer.xr.getCamera();
  25288. renderer.xr.updateCamera( camera );
  25289. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  25290. } else {
  25291. camera = this.camera;
  25292. pixelRatio = renderer.getPixelRatio();
  25293. renderer.getSize( _size );
  25294. }
  25295. this._pixelRatio = pixelRatio;
  25296. this.setSize( _size.width, _size.height );
  25297. const currentRenderTarget = renderer.getRenderTarget();
  25298. const currentMRT = renderer.getMRT();
  25299. const currentMask = camera.layers.mask;
  25300. this._cameraNear.value = camera.near;
  25301. this._cameraFar.value = camera.far;
  25302. if ( this._layers !== null ) {
  25303. camera.layers.mask = this._layers.mask;
  25304. }
  25305. for ( const name in this._previousTextures ) {
  25306. this.toggleTexture( name );
  25307. }
  25308. renderer.setRenderTarget( this.renderTarget );
  25309. renderer.setMRT( this._mrt );
  25310. renderer.render( scene, camera );
  25311. renderer.setRenderTarget( currentRenderTarget );
  25312. renderer.setMRT( currentMRT );
  25313. camera.layers.mask = currentMask;
  25314. }
  25315. /**
  25316. * Sets the size of the pass's render target. Honors the pixel ratio.
  25317. *
  25318. * @param {number} width - The width to set.
  25319. * @param {number} height - The height to set.
  25320. */
  25321. setSize( width, height ) {
  25322. this._width = width;
  25323. this._height = height;
  25324. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  25325. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  25326. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25327. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  25328. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  25329. }
  25330. /**
  25331. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  25332. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25333. * with `null` as the single argument.
  25334. *
  25335. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  25336. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  25337. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  25338. * @param {number} width - The width of the scissor box in logical pixel unit.
  25339. * @param {number} height - The height of the scissor box in logical pixel unit.
  25340. */
  25341. setScissor( x, y, width, height ) {
  25342. if ( x === null ) {
  25343. this._scissor = null;
  25344. } else {
  25345. if ( this._scissor === null ) this._scissor = new Vector4();
  25346. if ( x.isVector4 ) {
  25347. this._scissor.copy( x );
  25348. } else {
  25349. this._scissor.set( x, y, width, height );
  25350. }
  25351. this._scissor.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25352. }
  25353. }
  25354. /**
  25355. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  25356. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25357. * with `null` as the single argument.
  25358. *
  25359. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25360. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25361. * @param {number} width - The width of the viewport in logical pixel unit.
  25362. * @param {number} height - The height of the viewport in logical pixel unit.
  25363. */
  25364. setViewport( x, y, width, height ) {
  25365. if ( x === null ) {
  25366. this._viewport = null;
  25367. } else {
  25368. if ( this._viewport === null ) this._viewport = new Vector4();
  25369. if ( x.isVector4 ) {
  25370. this._viewport.copy( x );
  25371. } else {
  25372. this._viewport.set( x, y, width, height );
  25373. }
  25374. this._viewport.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25375. }
  25376. }
  25377. /**
  25378. * Sets the pixel ratio the pass's render target and updates the size.
  25379. *
  25380. * @param {number} pixelRatio - The pixel ratio to set.
  25381. */
  25382. setPixelRatio( pixelRatio ) {
  25383. this._pixelRatio = pixelRatio;
  25384. this.setSize( this._width, this._height );
  25385. }
  25386. /**
  25387. * Frees internal resources. Should be called when the node is no longer in use.
  25388. */
  25389. dispose() {
  25390. this.renderTarget.dispose();
  25391. }
  25392. }
  25393. /**
  25394. * @static
  25395. * @type {'color'}
  25396. * @default 'color'
  25397. */
  25398. PassNode.COLOR = 'color';
  25399. /**
  25400. * @static
  25401. * @type {'depth'}
  25402. * @default 'depth'
  25403. */
  25404. PassNode.DEPTH = 'depth';
  25405. /**
  25406. * TSL function for creating a pass node.
  25407. *
  25408. * @tsl
  25409. * @function
  25410. * @param {Scene} scene - A reference to the scene.
  25411. * @param {Camera} camera - A reference to the camera.
  25412. * @param {Object} options - Options for the internal render target.
  25413. * @returns {PassNode}
  25414. */
  25415. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  25416. /**
  25417. * TSL function for creating a pass texture node.
  25418. *
  25419. * @tsl
  25420. * @function
  25421. * @param {PassNode} pass - The pass node.
  25422. * @param {Texture} texture - The output texture.
  25423. * @returns {PassTextureNode}
  25424. */
  25425. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  25426. /**
  25427. * TSL function for creating a depth pass node.
  25428. *
  25429. * @tsl
  25430. * @function
  25431. * @param {Scene} scene - A reference to the scene.
  25432. * @param {Camera} camera - A reference to the camera.
  25433. * @param {Object} options - Options for the internal render target.
  25434. * @returns {PassNode}
  25435. */
  25436. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  25437. /**
  25438. * Represents a render pass for producing a toon outline effect on compatible objects.
  25439. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  25440. * will receive the outline.
  25441. *
  25442. * ```js
  25443. * const postProcessing = new PostProcessing( renderer );
  25444. *
  25445. * const scenePass = toonOutlinePass( scene, camera );
  25446. *
  25447. * postProcessing.outputNode = scenePass;
  25448. * ```
  25449. * @augments PassNode
  25450. */
  25451. class ToonOutlinePassNode extends PassNode {
  25452. static get type() {
  25453. return 'ToonOutlinePassNode';
  25454. }
  25455. /**
  25456. * Constructs a new outline pass node.
  25457. *
  25458. * @param {Scene} scene - A reference to the scene.
  25459. * @param {Camera} camera - A reference to the camera.
  25460. * @param {Node} colorNode - Defines the outline's color.
  25461. * @param {Node} thicknessNode - Defines the outline's thickness.
  25462. * @param {Node} alphaNode - Defines the outline's alpha.
  25463. */
  25464. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  25465. super( PassNode.COLOR, scene, camera );
  25466. /**
  25467. * Defines the outline's color.
  25468. *
  25469. * @type {Node}
  25470. */
  25471. this.colorNode = colorNode;
  25472. /**
  25473. * Defines the outline's thickness.
  25474. *
  25475. * @type {Node}
  25476. */
  25477. this.thicknessNode = thicknessNode;
  25478. /**
  25479. * Defines the outline's alpha.
  25480. *
  25481. * @type {Node}
  25482. */
  25483. this.alphaNode = alphaNode;
  25484. /**
  25485. * An internal material cache.
  25486. *
  25487. * @private
  25488. * @type {WeakMap<Material, NodeMaterial>}
  25489. */
  25490. this._materialCache = new WeakMap();
  25491. }
  25492. updateBefore( frame ) {
  25493. const { renderer } = frame;
  25494. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25495. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  25496. // only render outline for supported materials
  25497. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  25498. if ( material.wireframe === false ) {
  25499. const outlineMaterial = this._getOutlineMaterial( material );
  25500. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  25501. }
  25502. }
  25503. // default
  25504. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  25505. } );
  25506. super.updateBefore( frame );
  25507. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25508. }
  25509. /**
  25510. * Creates the material used for outline rendering.
  25511. *
  25512. * @private
  25513. * @return {NodeMaterial} The outline material.
  25514. */
  25515. _createMaterial() {
  25516. const material = new NodeMaterial();
  25517. material.isMeshToonOutlineMaterial = true;
  25518. material.name = 'Toon_Outline';
  25519. material.side = BackSide;
  25520. // vertex node
  25521. const outlineNormal = normalLocal.negate();
  25522. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  25523. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  25524. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  25525. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  25526. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  25527. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  25528. // color node
  25529. material.colorNode = vec4( this.colorNode, this.alphaNode );
  25530. return material;
  25531. }
  25532. /**
  25533. * For the given toon material, this method returns a corresponding
  25534. * outline material.
  25535. *
  25536. * @private
  25537. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  25538. * @return {NodeMaterial} The outline material.
  25539. */
  25540. _getOutlineMaterial( originalMaterial ) {
  25541. let outlineMaterial = this._materialCache.get( originalMaterial );
  25542. if ( outlineMaterial === undefined ) {
  25543. outlineMaterial = this._createMaterial();
  25544. this._materialCache.set( originalMaterial, outlineMaterial );
  25545. }
  25546. return outlineMaterial;
  25547. }
  25548. }
  25549. /**
  25550. * TSL function for creating a toon outline pass node.
  25551. *
  25552. * @tsl
  25553. * @function
  25554. * @param {Scene} scene - A reference to the scene.
  25555. * @param {Camera} camera - A reference to the camera.
  25556. * @param {Color} color - Defines the outline's color.
  25557. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  25558. * @param {number} [alpha=1] - Defines the outline's alpha.
  25559. * @returns {ToonOutlinePassNode}
  25560. */
  25561. 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 ) ) );
  25562. /**
  25563. * Linear tone mapping, exposure only.
  25564. *
  25565. * @tsl
  25566. * @function
  25567. * @param {Node<vec3>} color - The color that should be tone mapped.
  25568. * @param {Node<float>} exposure - The exposure.
  25569. * @return {Node<vec3>} The tone mapped color.
  25570. */
  25571. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25572. return color.mul( exposure ).clamp();
  25573. } ).setLayout( {
  25574. name: 'linearToneMapping',
  25575. type: 'vec3',
  25576. inputs: [
  25577. { name: 'color', type: 'vec3' },
  25578. { name: 'exposure', type: 'float' }
  25579. ]
  25580. } );
  25581. /**
  25582. * Reinhard tone mapping.
  25583. *
  25584. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  25585. *
  25586. * @tsl
  25587. * @function
  25588. * @param {Node<vec3>} color - The color that should be tone mapped.
  25589. * @param {Node<float>} exposure - The exposure.
  25590. * @return {Node<vec3>} The tone mapped color.
  25591. */
  25592. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25593. color = color.mul( exposure );
  25594. return color.div( color.add( 1.0 ) ).clamp();
  25595. } ).setLayout( {
  25596. name: 'reinhardToneMapping',
  25597. type: 'vec3',
  25598. inputs: [
  25599. { name: 'color', type: 'vec3' },
  25600. { name: 'exposure', type: 'float' }
  25601. ]
  25602. } );
  25603. /**
  25604. * Cineon tone mapping.
  25605. *
  25606. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  25607. *
  25608. * @tsl
  25609. * @function
  25610. * @param {Node<vec3>} color - The color that should be tone mapped.
  25611. * @param {Node<float>} exposure - The exposure.
  25612. * @return {Node<vec3>} The tone mapped color.
  25613. */
  25614. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25615. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  25616. color = color.mul( exposure );
  25617. color = color.sub( 0.004 ).max( 0.0 );
  25618. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  25619. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  25620. return a.div( b ).pow( 2.2 );
  25621. } ).setLayout( {
  25622. name: 'cineonToneMapping',
  25623. type: 'vec3',
  25624. inputs: [
  25625. { name: 'color', type: 'vec3' },
  25626. { name: 'exposure', type: 'float' }
  25627. ]
  25628. } );
  25629. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  25630. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25631. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  25632. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  25633. return a.div( b );
  25634. } );
  25635. /**
  25636. * ACESFilmic tone mapping.
  25637. *
  25638. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  25639. *
  25640. * @tsl
  25641. * @function
  25642. * @param {Node<vec3>} color - The color that should be tone mapped.
  25643. * @param {Node<float>} exposure - The exposure.
  25644. * @return {Node<vec3>} The tone mapped color.
  25645. */
  25646. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25647. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  25648. const ACESInputMat = mat3(
  25649. 0.59719, 0.35458, 0.04823,
  25650. 0.07600, 0.90834, 0.01566,
  25651. 0.02840, 0.13383, 0.83777
  25652. );
  25653. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  25654. const ACESOutputMat = mat3(
  25655. 1.60475, -0.53108, -0.07367,
  25656. -0.10208, 1.10813, -605e-5,
  25657. -327e-5, -0.07276, 1.07602
  25658. );
  25659. color = color.mul( exposure ).div( 0.6 );
  25660. color = ACESInputMat.mul( color );
  25661. // Apply RRT and ODT
  25662. color = RRTAndODTFit( color );
  25663. color = ACESOutputMat.mul( color );
  25664. // Clamp to [0, 1]
  25665. return color.clamp();
  25666. } ).setLayout( {
  25667. name: 'acesFilmicToneMapping',
  25668. type: 'vec3',
  25669. inputs: [
  25670. { name: 'color', type: 'vec3' },
  25671. { name: 'exposure', type: 'float' }
  25672. ]
  25673. } );
  25674. 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 ) );
  25675. 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 ) );
  25676. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25677. const x = vec3( x_immutable ).toVar();
  25678. const x2 = vec3( x.mul( x ) ).toVar();
  25679. const x4 = vec3( x2.mul( x2 ) ).toVar();
  25680. 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 ) ) ) );
  25681. } );
  25682. /**
  25683. * AgX tone mapping.
  25684. *
  25685. * @tsl
  25686. * @function
  25687. * @param {Node<vec3>} color - The color that should be tone mapped.
  25688. * @param {Node<float>} exposure - The exposure.
  25689. * @return {Node<vec3>} The tone mapped color.
  25690. */
  25691. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25692. const colortone = vec3( color ).toVar();
  25693. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  25694. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  25695. const AgxMinEv = float( -12.47393 );
  25696. const AgxMaxEv = float( 4.026069 );
  25697. colortone.mulAssign( exposure );
  25698. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  25699. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  25700. colortone.assign( max$1( colortone, 1e-10 ) );
  25701. colortone.assign( log2( colortone ) );
  25702. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  25703. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25704. colortone.assign( agxDefaultContrastApprox( colortone ) );
  25705. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  25706. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  25707. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  25708. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25709. return colortone;
  25710. } ).setLayout( {
  25711. name: 'agxToneMapping',
  25712. type: 'vec3',
  25713. inputs: [
  25714. { name: 'color', type: 'vec3' },
  25715. { name: 'exposure', type: 'float' }
  25716. ]
  25717. } );
  25718. /**
  25719. * Neutral tone mapping.
  25720. *
  25721. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  25722. *
  25723. * @tsl
  25724. * @function
  25725. * @param {Node<vec3>} color - The color that should be tone mapped.
  25726. * @param {Node<float>} exposure - The exposure.
  25727. * @return {Node<vec3>} The tone mapped color.
  25728. */
  25729. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25730. const StartCompression = float( 0.8 - 0.04 );
  25731. const Desaturation = float( 0.15 );
  25732. color = color.mul( exposure );
  25733. const x = min$1( color.r, min$1( color.g, color.b ) );
  25734. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  25735. color.subAssign( offset );
  25736. const peak = max$1( color.r, max$1( color.g, color.b ) );
  25737. If( peak.lessThan( StartCompression ), () => {
  25738. return color;
  25739. } );
  25740. const d = sub( 1, StartCompression );
  25741. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  25742. color.mulAssign( newPeak.div( peak ) );
  25743. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  25744. return mix( color, vec3( newPeak ), g );
  25745. } ).setLayout( {
  25746. name: 'neutralToneMapping',
  25747. type: 'vec3',
  25748. inputs: [
  25749. { name: 'color', type: 'vec3' },
  25750. { name: 'exposure', type: 'float' }
  25751. ]
  25752. } );
  25753. /**
  25754. * This class represents native code sections. It is the base
  25755. * class for modules like {@link FunctionNode} which allows to implement
  25756. * functions with native shader languages.
  25757. *
  25758. * @augments Node
  25759. */
  25760. class CodeNode extends Node {
  25761. static get type() {
  25762. return 'CodeNode';
  25763. }
  25764. /**
  25765. * Constructs a new code node.
  25766. *
  25767. * @param {string} [code=''] - The native code.
  25768. * @param {Array<Node>} [includes=[]] - An array of includes.
  25769. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25770. */
  25771. constructor( code = '', includes = [], language = '' ) {
  25772. super( 'code' );
  25773. /**
  25774. * This flag can be used for type testing.
  25775. *
  25776. * @type {boolean}
  25777. * @readonly
  25778. * @default true
  25779. */
  25780. this.isCodeNode = true;
  25781. /**
  25782. * This flag is used for global cache.
  25783. *
  25784. * @type {boolean}
  25785. * @default true
  25786. */
  25787. this.global = true;
  25788. /**
  25789. * The native code.
  25790. *
  25791. * @type {string}
  25792. * @default ''
  25793. */
  25794. this.code = code;
  25795. /**
  25796. * An array of includes
  25797. *
  25798. * @type {Array<Node>}
  25799. * @default []
  25800. */
  25801. this.includes = includes;
  25802. /**
  25803. * The used language.
  25804. *
  25805. * @type {('js'|'wgsl'|'glsl')}
  25806. * @default ''
  25807. */
  25808. this.language = language;
  25809. }
  25810. /**
  25811. * Sets the includes of this code node.
  25812. *
  25813. * @param {Array<Node>} includes - The includes to set.
  25814. * @return {CodeNode} A reference to this node.
  25815. */
  25816. setIncludes( includes ) {
  25817. this.includes = includes;
  25818. return this;
  25819. }
  25820. /**
  25821. * Returns the includes of this code node.
  25822. *
  25823. * @param {NodeBuilder} builder - The current node builder.
  25824. * @return {Array<Node>} The includes.
  25825. */
  25826. getIncludes( /*builder*/ ) {
  25827. return this.includes;
  25828. }
  25829. generate( builder ) {
  25830. const includes = this.getIncludes( builder );
  25831. for ( const include of includes ) {
  25832. include.build( builder );
  25833. }
  25834. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  25835. nodeCode.code = this.code;
  25836. return nodeCode.code;
  25837. }
  25838. serialize( data ) {
  25839. super.serialize( data );
  25840. data.code = this.code;
  25841. data.language = this.language;
  25842. }
  25843. deserialize( data ) {
  25844. super.deserialize( data );
  25845. this.code = data.code;
  25846. this.language = data.language;
  25847. }
  25848. }
  25849. /**
  25850. * TSL function for creating a code node.
  25851. *
  25852. * @tsl
  25853. * @function
  25854. * @param {string} [code] - The native code.
  25855. * @param {?Array<Node>} [includes=[]] - An array of includes.
  25856. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25857. * @returns {CodeNode}
  25858. */
  25859. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  25860. /**
  25861. * TSL function for creating a JS code node.
  25862. *
  25863. * @tsl
  25864. * @function
  25865. * @param {string} src - The native code.
  25866. * @param {Array<Node>} includes - An array of includes.
  25867. * @returns {CodeNode}
  25868. */
  25869. const js = ( src, includes ) => code( src, includes, 'js' );
  25870. /**
  25871. * TSL function for creating a WGSL code node.
  25872. *
  25873. * @tsl
  25874. * @function
  25875. * @param {string} src - The native code.
  25876. * @param {Array<Node>} includes - An array of includes.
  25877. * @returns {CodeNode}
  25878. */
  25879. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  25880. /**
  25881. * TSL function for creating a GLSL code node.
  25882. *
  25883. * @tsl
  25884. * @function
  25885. * @param {string} src - The native code.
  25886. * @param {Array<Node>} includes - An array of includes.
  25887. * @returns {CodeNode}
  25888. */
  25889. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  25890. /**
  25891. * This class represents a native shader function. It can be used to implement
  25892. * certain aspects of a node material with native shader code. There are two predefined
  25893. * TSL functions for easier usage.
  25894. *
  25895. * - `wgslFn`: Creates a WGSL function node.
  25896. * - `glslFn`: Creates a GLSL function node.
  25897. *
  25898. * A basic example with one include looks like so:
  25899. *
  25900. * ```js
  25901. * const desaturateWGSLFn = wgslFn( `
  25902. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  25903. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  25904. * return vec3<f32>( dot( lum, color ) );
  25905. * }`
  25906. *);
  25907. * const someWGSLFn = wgslFn( `
  25908. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  25909. * return desaturate( color );
  25910. * }
  25911. * `, [ desaturateWGSLFn ] );
  25912. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  25913. *```
  25914. * @augments CodeNode
  25915. */
  25916. class FunctionNode extends CodeNode {
  25917. static get type() {
  25918. return 'FunctionNode';
  25919. }
  25920. /**
  25921. * Constructs a new function node.
  25922. *
  25923. * @param {string} [code=''] - The native code.
  25924. * @param {Array<Node>} [includes=[]] - An array of includes.
  25925. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25926. */
  25927. constructor( code = '', includes = [], language = '' ) {
  25928. super( code, includes, language );
  25929. }
  25930. getNodeType( builder ) {
  25931. return this.getNodeFunction( builder ).type;
  25932. }
  25933. /**
  25934. * Returns the inputs of this function node.
  25935. *
  25936. * @param {NodeBuilder} builder - The current node builder.
  25937. * @return {Array<NodeFunctionInput>} The inputs.
  25938. */
  25939. getInputs( builder ) {
  25940. return this.getNodeFunction( builder ).inputs;
  25941. }
  25942. /**
  25943. * Returns the node function for this function node.
  25944. *
  25945. * @param {NodeBuilder} builder - The current node builder.
  25946. * @return {NodeFunction} The node function.
  25947. */
  25948. getNodeFunction( builder ) {
  25949. const nodeData = builder.getDataFromNode( this );
  25950. let nodeFunction = nodeData.nodeFunction;
  25951. if ( nodeFunction === undefined ) {
  25952. nodeFunction = builder.parser.parseFunction( this.code );
  25953. nodeData.nodeFunction = nodeFunction;
  25954. }
  25955. return nodeFunction;
  25956. }
  25957. generate( builder, output ) {
  25958. super.generate( builder );
  25959. const nodeFunction = this.getNodeFunction( builder );
  25960. const name = nodeFunction.name;
  25961. const type = nodeFunction.type;
  25962. const nodeCode = builder.getCodeFromNode( this, type );
  25963. if ( name !== '' ) {
  25964. // use a custom property name
  25965. nodeCode.name = name;
  25966. }
  25967. const propertyName = builder.getPropertyName( nodeCode );
  25968. const code = this.getNodeFunction( builder ).getCode( propertyName );
  25969. nodeCode.code = code + '\n';
  25970. if ( output === 'property' ) {
  25971. return propertyName;
  25972. } else {
  25973. return builder.format( `${ propertyName }()`, type, output );
  25974. }
  25975. }
  25976. }
  25977. const nativeFn = ( code, includes = [], language = '' ) => {
  25978. for ( let i = 0; i < includes.length; i ++ ) {
  25979. const include = includes[ i ];
  25980. // TSL Function: glslFn, wgslFn
  25981. if ( typeof include === 'function' ) {
  25982. includes[ i ] = include.functionNode;
  25983. }
  25984. }
  25985. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  25986. const fn = ( ...params ) => functionNode.call( ...params );
  25987. fn.functionNode = functionNode;
  25988. return fn;
  25989. };
  25990. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  25991. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  25992. /**
  25993. * `ScriptableNode` uses this class to manage script inputs and outputs.
  25994. *
  25995. * @augments Node
  25996. */
  25997. class ScriptableValueNode extends Node {
  25998. static get type() {
  25999. return 'ScriptableValueNode';
  26000. }
  26001. /**
  26002. * Constructs a new scriptable node.
  26003. *
  26004. * @param {any} [value=null] - The value.
  26005. */
  26006. constructor( value = null ) {
  26007. super();
  26008. /**
  26009. * A reference to the value.
  26010. *
  26011. * @private
  26012. * @default null
  26013. */
  26014. this._value = value;
  26015. /**
  26016. * Depending on the type of `_value`, this property might cache parsed data.
  26017. *
  26018. * @private
  26019. * @default null
  26020. */
  26021. this._cache = null;
  26022. /**
  26023. * If this node represents an input, this property represents the input type.
  26024. *
  26025. * @type {?string}
  26026. * @default null
  26027. */
  26028. this.inputType = null;
  26029. /**
  26030. * If this node represents an output, this property represents the output type.
  26031. *
  26032. * @type {?string}
  26033. * @default null
  26034. */
  26035. this.outputType = null;
  26036. /**
  26037. * An event dispatcher for managing events.
  26038. *
  26039. * @type {EventDispatcher}
  26040. */
  26041. this.events = new EventDispatcher();
  26042. /**
  26043. * This flag can be used for type testing.
  26044. *
  26045. * @type {boolean}
  26046. * @readonly
  26047. * @default true
  26048. */
  26049. this.isScriptableValueNode = true;
  26050. }
  26051. /**
  26052. * Whether this node represents an output or not.
  26053. *
  26054. * @type {boolean}
  26055. * @readonly
  26056. * @default true
  26057. */
  26058. get isScriptableOutputNode() {
  26059. return this.outputType !== null;
  26060. }
  26061. set value( val ) {
  26062. if ( this._value === val ) return;
  26063. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  26064. URL.revokeObjectURL( this._cache );
  26065. this._cache = null;
  26066. }
  26067. this._value = val;
  26068. this.events.dispatchEvent( { type: 'change' } );
  26069. this.refresh();
  26070. }
  26071. /**
  26072. * The node's value.
  26073. *
  26074. * @type {any}
  26075. */
  26076. get value() {
  26077. return this._value;
  26078. }
  26079. /**
  26080. * Dispatches the `refresh` event.
  26081. */
  26082. refresh() {
  26083. this.events.dispatchEvent( { type: 'refresh' } );
  26084. }
  26085. /**
  26086. * The `value` property usually represents a node or even binary data in form of array buffers.
  26087. * In this case, this method tries to return the actual value behind the complex type.
  26088. *
  26089. * @return {any} The value.
  26090. */
  26091. getValue() {
  26092. const value = this.value;
  26093. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  26094. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  26095. } else if ( value && value.value !== null && value.value !== undefined && (
  26096. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  26097. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  26098. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  26099. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  26100. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  26101. ( this.inputType === 'Color' && value.value.isColor ) ||
  26102. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  26103. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  26104. ) ) {
  26105. return value.value;
  26106. }
  26107. return this._cache || value;
  26108. }
  26109. /**
  26110. * Overwritten since the node type is inferred from the value.
  26111. *
  26112. * @param {NodeBuilder} builder - The current node builder.
  26113. * @return {string} The node type.
  26114. */
  26115. getNodeType( builder ) {
  26116. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  26117. }
  26118. setup() {
  26119. return this.value && this.value.isNode ? this.value : float();
  26120. }
  26121. serialize( data ) {
  26122. super.serialize( data );
  26123. if ( this.value !== null ) {
  26124. if ( this.inputType === 'ArrayBuffer' ) {
  26125. data.value = arrayBufferToBase64( this.value );
  26126. } else {
  26127. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  26128. }
  26129. } else {
  26130. data.value = null;
  26131. }
  26132. data.inputType = this.inputType;
  26133. data.outputType = this.outputType;
  26134. }
  26135. deserialize( data ) {
  26136. super.deserialize( data );
  26137. let value = null;
  26138. if ( data.value !== null ) {
  26139. if ( data.inputType === 'ArrayBuffer' ) {
  26140. value = base64ToArrayBuffer( data.value );
  26141. } else if ( data.inputType === 'Texture' ) {
  26142. value = data.meta.textures[ data.value ];
  26143. } else {
  26144. value = data.meta.nodes[ data.value ] || null;
  26145. }
  26146. }
  26147. this.value = value;
  26148. this.inputType = data.inputType;
  26149. this.outputType = data.outputType;
  26150. }
  26151. }
  26152. /**
  26153. * TSL function for creating a scriptable value node.
  26154. *
  26155. * @tsl
  26156. * @function
  26157. * @param {any} [value] - The value.
  26158. * @returns {ScriptableValueNode}
  26159. */
  26160. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  26161. /**
  26162. * A Map-like data structure for managing resources of scriptable nodes.
  26163. *
  26164. * @augments Map
  26165. */
  26166. class Resources extends Map {
  26167. get( key, callback = null, ...params ) {
  26168. if ( this.has( key ) ) return super.get( key );
  26169. if ( callback !== null ) {
  26170. const value = callback( ...params );
  26171. this.set( key, value );
  26172. return value;
  26173. }
  26174. }
  26175. }
  26176. class Parameters {
  26177. constructor( scriptableNode ) {
  26178. this.scriptableNode = scriptableNode;
  26179. }
  26180. get parameters() {
  26181. return this.scriptableNode.parameters;
  26182. }
  26183. get layout() {
  26184. return this.scriptableNode.getLayout();
  26185. }
  26186. getInputLayout( id ) {
  26187. return this.scriptableNode.getInputLayout( id );
  26188. }
  26189. get( name ) {
  26190. const param = this.parameters[ name ];
  26191. const value = param ? param.getValue() : null;
  26192. return value;
  26193. }
  26194. }
  26195. /**
  26196. * Defines the resources (e.g. namespaces) of scriptable nodes.
  26197. *
  26198. * @type {Resources}
  26199. */
  26200. const ScriptableNodeResources = new Resources();
  26201. /**
  26202. * This type of node allows to implement nodes with custom scripts. The script
  26203. * section is represented as an instance of `CodeNode` written with JavaScript.
  26204. * The script itself must adhere to a specific structure.
  26205. *
  26206. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  26207. * - layout: The layout object defines the script's interface (inputs and outputs).
  26208. *
  26209. * ```js
  26210. * ScriptableNodeResources.set( 'TSL', TSL );
  26211. *
  26212. * const scriptableNode = scriptable( js( `
  26213. * layout = {
  26214. * outputType: 'node',
  26215. * elements: [
  26216. * { name: 'source', inputType: 'node' },
  26217. * ]
  26218. * };
  26219. *
  26220. * const { mul, oscSine } = TSL;
  26221. *
  26222. * function main() {
  26223. * const source = parameters.get( 'source' ) || float();
  26224. * return mul( source, oscSine() ) );
  26225. * }
  26226. *
  26227. * ` ) );
  26228. *
  26229. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  26230. *
  26231. * const material = new THREE.MeshBasicNodeMaterial();
  26232. * material.colorNode = scriptableNode;
  26233. * ```
  26234. *
  26235. * @augments Node
  26236. */
  26237. class ScriptableNode extends Node {
  26238. static get type() {
  26239. return 'ScriptableNode';
  26240. }
  26241. /**
  26242. * Constructs a new scriptable node.
  26243. *
  26244. * @param {?CodeNode} [codeNode=null] - The code node.
  26245. * @param {Object} [parameters={}] - The parameters definition.
  26246. */
  26247. constructor( codeNode = null, parameters = {} ) {
  26248. super();
  26249. /**
  26250. * The code node.
  26251. *
  26252. * @type {?CodeNode}
  26253. * @default null
  26254. */
  26255. this.codeNode = codeNode;
  26256. /**
  26257. * The parameters definition.
  26258. *
  26259. * @type {Object}
  26260. * @default {}
  26261. */
  26262. this.parameters = parameters;
  26263. this._local = new Resources();
  26264. this._output = scriptableValue( null );
  26265. this._outputs = {};
  26266. this._source = this.source;
  26267. this._method = null;
  26268. this._object = null;
  26269. this._value = null;
  26270. this._needsOutputUpdate = true;
  26271. this.onRefresh = this.onRefresh.bind( this );
  26272. /**
  26273. * This flag can be used for type testing.
  26274. *
  26275. * @type {boolean}
  26276. * @readonly
  26277. * @default true
  26278. */
  26279. this.isScriptableNode = true;
  26280. }
  26281. /**
  26282. * The source code of the scriptable node.
  26283. *
  26284. * @type {string}
  26285. */
  26286. get source() {
  26287. return this.codeNode ? this.codeNode.code : '';
  26288. }
  26289. /**
  26290. * Sets the reference of a local script variable.
  26291. *
  26292. * @param {string} name - The variable name.
  26293. * @param {Object} value - The reference to set.
  26294. * @return {Resources} The resource map
  26295. */
  26296. setLocal( name, value ) {
  26297. return this._local.set( name, value );
  26298. }
  26299. /**
  26300. * Gets the value of a local script variable.
  26301. *
  26302. * @param {string} name - The variable name.
  26303. * @return {Object} The value.
  26304. */
  26305. getLocal( name ) {
  26306. return this._local.get( name );
  26307. }
  26308. /**
  26309. * Event listener for the `refresh` event.
  26310. */
  26311. onRefresh() {
  26312. this._refresh();
  26313. }
  26314. /**
  26315. * Returns an input from the layout with the given id/name.
  26316. *
  26317. * @param {string} id - The id/name of the input.
  26318. * @return {Object} The element entry.
  26319. */
  26320. getInputLayout( id ) {
  26321. for ( const element of this.getLayout() ) {
  26322. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  26323. return element;
  26324. }
  26325. }
  26326. }
  26327. /**
  26328. * Returns an output from the layout with the given id/name.
  26329. *
  26330. * @param {string} id - The id/name of the output.
  26331. * @return {Object} The element entry.
  26332. */
  26333. getOutputLayout( id ) {
  26334. for ( const element of this.getLayout() ) {
  26335. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  26336. return element;
  26337. }
  26338. }
  26339. }
  26340. /**
  26341. * Defines a script output for the given name and value.
  26342. *
  26343. * @param {string} name - The name of the output.
  26344. * @param {Node} value - The node value.
  26345. * @return {ScriptableNode} A reference to this node.
  26346. */
  26347. setOutput( name, value ) {
  26348. const outputs = this._outputs;
  26349. if ( outputs[ name ] === undefined ) {
  26350. outputs[ name ] = scriptableValue( value );
  26351. } else {
  26352. outputs[ name ].value = value;
  26353. }
  26354. return this;
  26355. }
  26356. /**
  26357. * Returns a script output for the given name.
  26358. *
  26359. * @param {string} name - The name of the output.
  26360. * @return {ScriptableValueNode} The node value.
  26361. */
  26362. getOutput( name ) {
  26363. return this._outputs[ name ];
  26364. }
  26365. /**
  26366. * Returns a parameter for the given name
  26367. *
  26368. * @param {string} name - The name of the parameter.
  26369. * @return {ScriptableValueNode} The node value.
  26370. */
  26371. getParameter( name ) {
  26372. return this.parameters[ name ];
  26373. }
  26374. /**
  26375. * Sets a value for the given parameter name.
  26376. *
  26377. * @param {string} name - The parameter name.
  26378. * @param {any} value - The parameter value.
  26379. * @return {ScriptableNode} A reference to this node.
  26380. */
  26381. setParameter( name, value ) {
  26382. const parameters = this.parameters;
  26383. if ( value && value.isScriptableNode ) {
  26384. this.deleteParameter( name );
  26385. parameters[ name ] = value;
  26386. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  26387. } else if ( value && value.isScriptableValueNode ) {
  26388. this.deleteParameter( name );
  26389. parameters[ name ] = value;
  26390. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26391. } else if ( parameters[ name ] === undefined ) {
  26392. parameters[ name ] = scriptableValue( value );
  26393. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26394. } else {
  26395. parameters[ name ].value = value;
  26396. }
  26397. return this;
  26398. }
  26399. /**
  26400. * Returns the value of this node which is the value of
  26401. * the default output.
  26402. *
  26403. * @return {Node} The value.
  26404. */
  26405. getValue() {
  26406. return this.getDefaultOutput().getValue();
  26407. }
  26408. /**
  26409. * Deletes a parameter from the script.
  26410. *
  26411. * @param {string} name - The parameter to remove.
  26412. * @return {ScriptableNode} A reference to this node.
  26413. */
  26414. deleteParameter( name ) {
  26415. let valueNode = this.parameters[ name ];
  26416. if ( valueNode ) {
  26417. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  26418. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  26419. }
  26420. return this;
  26421. }
  26422. /**
  26423. * Deletes all parameters from the script.
  26424. *
  26425. * @return {ScriptableNode} A reference to this node.
  26426. */
  26427. clearParameters() {
  26428. for ( const name of Object.keys( this.parameters ) ) {
  26429. this.deleteParameter( name );
  26430. }
  26431. this.needsUpdate = true;
  26432. return this;
  26433. }
  26434. /**
  26435. * Calls a function from the script.
  26436. *
  26437. * @param {string} name - The function name.
  26438. * @param {...any} params - A list of parameters.
  26439. * @return {any} The result of the function call.
  26440. */
  26441. call( name, ...params ) {
  26442. const object = this.getObject();
  26443. const method = object[ name ];
  26444. if ( typeof method === 'function' ) {
  26445. return method( ...params );
  26446. }
  26447. }
  26448. /**
  26449. * Asynchronously calls a function from the script.
  26450. *
  26451. * @param {string} name - The function name.
  26452. * @param {...any} params - A list of parameters.
  26453. * @return {Promise<any>} The result of the function call.
  26454. */
  26455. async callAsync( name, ...params ) {
  26456. const object = this.getObject();
  26457. const method = object[ name ];
  26458. if ( typeof method === 'function' ) {
  26459. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  26460. }
  26461. }
  26462. /**
  26463. * Overwritten since the node types is inferred from the script's output.
  26464. *
  26465. * @param {NodeBuilder} builder - The current node builder
  26466. * @return {string} The node type.
  26467. */
  26468. getNodeType( builder ) {
  26469. return this.getDefaultOutputNode().getNodeType( builder );
  26470. }
  26471. /**
  26472. * Refreshes the script node.
  26473. *
  26474. * @param {?string} [output=null] - An optional output.
  26475. */
  26476. refresh( output = null ) {
  26477. if ( output !== null ) {
  26478. this.getOutput( output ).refresh();
  26479. } else {
  26480. this._refresh();
  26481. }
  26482. }
  26483. /**
  26484. * Returns an object representation of the script.
  26485. *
  26486. * @return {Object} The result object.
  26487. */
  26488. getObject() {
  26489. if ( this.needsUpdate ) this.dispose();
  26490. if ( this._object !== null ) return this._object;
  26491. //
  26492. const refresh = () => this.refresh();
  26493. const setOutput = ( id, value ) => this.setOutput( id, value );
  26494. const parameters = new Parameters( this );
  26495. const THREE = ScriptableNodeResources.get( 'THREE' );
  26496. const TSL = ScriptableNodeResources.get( 'TSL' );
  26497. const method = this.getMethod();
  26498. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  26499. this._object = method( ...params );
  26500. const layout = this._object.layout;
  26501. if ( layout ) {
  26502. if ( layout.cache === false ) {
  26503. this._local.clear();
  26504. }
  26505. // default output
  26506. this._output.outputType = layout.outputType || null;
  26507. if ( Array.isArray( layout.elements ) ) {
  26508. for ( const element of layout.elements ) {
  26509. const id = element.id || element.name;
  26510. if ( element.inputType ) {
  26511. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  26512. this.getParameter( id ).inputType = element.inputType;
  26513. }
  26514. if ( element.outputType ) {
  26515. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  26516. this.getOutput( id ).outputType = element.outputType;
  26517. }
  26518. }
  26519. }
  26520. }
  26521. return this._object;
  26522. }
  26523. deserialize( data ) {
  26524. super.deserialize( data );
  26525. for ( const name in this.parameters ) {
  26526. let valueNode = this.parameters[ name ];
  26527. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  26528. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  26529. }
  26530. }
  26531. /**
  26532. * Returns the layout of the script.
  26533. *
  26534. * @return {Object} The script's layout.
  26535. */
  26536. getLayout() {
  26537. return this.getObject().layout;
  26538. }
  26539. /**
  26540. * Returns default node output of the script.
  26541. *
  26542. * @return {Node} The default node output.
  26543. */
  26544. getDefaultOutputNode() {
  26545. const output = this.getDefaultOutput().value;
  26546. if ( output && output.isNode ) {
  26547. return output;
  26548. }
  26549. return float();
  26550. }
  26551. /**
  26552. * Returns default output of the script.
  26553. *
  26554. * @return {ScriptableValueNode} The default output.
  26555. */
  26556. getDefaultOutput() {
  26557. return this._exec()._output;
  26558. }
  26559. /**
  26560. * Returns a function created from the node's script.
  26561. *
  26562. * @return {Function} The function representing the node's code.
  26563. */
  26564. getMethod() {
  26565. if ( this.needsUpdate ) this.dispose();
  26566. if ( this._method !== null ) return this._method;
  26567. //
  26568. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  26569. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  26570. const properties = interfaceProps.join( ', ' );
  26571. const declarations = 'var ' + properties + '; var output = {};\n';
  26572. const returns = '\nreturn { ...output, ' + properties + ' };';
  26573. const code = declarations + this.codeNode.code + returns;
  26574. //
  26575. this._method = new Function( ...parametersProps, code );
  26576. return this._method;
  26577. }
  26578. /**
  26579. * Frees all internal resources.
  26580. */
  26581. dispose() {
  26582. if ( this._method === null ) return;
  26583. if ( this._object && typeof this._object.dispose === 'function' ) {
  26584. this._object.dispose();
  26585. }
  26586. this._method = null;
  26587. this._object = null;
  26588. this._source = null;
  26589. this._value = null;
  26590. this._needsOutputUpdate = true;
  26591. this._output.value = null;
  26592. this._outputs = {};
  26593. }
  26594. setup() {
  26595. return this.getDefaultOutputNode();
  26596. }
  26597. getCacheKey( force ) {
  26598. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  26599. for ( const param in this.parameters ) {
  26600. values.push( this.parameters[ param ].getCacheKey( force ) );
  26601. }
  26602. return hashArray( values );
  26603. }
  26604. set needsUpdate( value ) {
  26605. if ( value === true ) this.dispose();
  26606. }
  26607. get needsUpdate() {
  26608. return this.source !== this._source;
  26609. }
  26610. /**
  26611. * Executes the `main` function of the script.
  26612. *
  26613. * @private
  26614. * @return {ScriptableNode} A reference to this node.
  26615. */
  26616. _exec() {
  26617. if ( this.codeNode === null ) return this;
  26618. if ( this._needsOutputUpdate === true ) {
  26619. this._value = this.call( 'main' );
  26620. this._needsOutputUpdate = false;
  26621. }
  26622. this._output.value = this._value;
  26623. return this;
  26624. }
  26625. /**
  26626. * Executes the refresh.
  26627. *
  26628. * @private
  26629. */
  26630. _refresh() {
  26631. this.needsUpdate = true;
  26632. this._exec();
  26633. this._output.refresh();
  26634. }
  26635. }
  26636. /**
  26637. * TSL function for creating a scriptable node.
  26638. *
  26639. * @tsl
  26640. * @function
  26641. * @param {CodeNode} [codeNode] - The code node.
  26642. * @param {?Object} [parameters={}] - The parameters definition.
  26643. * @returns {ScriptableNode}
  26644. */
  26645. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  26646. /**
  26647. * Returns a node that represents the `z` coordinate in view space
  26648. * for the current fragment. It's a different representation of the
  26649. * default depth value.
  26650. *
  26651. * This value can be part of a computation that defines how the fog
  26652. * density increases when moving away from the camera.
  26653. *
  26654. * @param {NodeBuilder} builder - The current node builder.
  26655. * @return {Node} The viewZ node.
  26656. */
  26657. function getViewZNode( builder ) {
  26658. let viewZ;
  26659. const getViewZ = builder.context.getViewZ;
  26660. if ( getViewZ !== undefined ) {
  26661. viewZ = getViewZ( this );
  26662. }
  26663. return ( viewZ || positionView.z ).negate();
  26664. }
  26665. /**
  26666. * Constructs a new range factor node.
  26667. *
  26668. * @tsl
  26669. * @function
  26670. * @param {Node} near - Defines the near value.
  26671. * @param {Node} far - Defines the far value.
  26672. */
  26673. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  26674. const viewZ = getViewZNode( builder );
  26675. return smoothstep( near, far, viewZ );
  26676. } );
  26677. /**
  26678. * Represents an exponential squared fog. This type of fog gives
  26679. * a clear view near the camera and a faster than exponentially
  26680. * densening fog farther from the camera.
  26681. *
  26682. * @tsl
  26683. * @function
  26684. * @param {Node} density - Defines the fog density.
  26685. */
  26686. const densityFogFactor = Fn( ( [ density ], builder ) => {
  26687. const viewZ = getViewZNode( builder );
  26688. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  26689. } );
  26690. /**
  26691. * This class can be used to configure a fog for the scene.
  26692. * Nodes of this type are assigned to `Scene.fogNode`.
  26693. *
  26694. * @tsl
  26695. * @function
  26696. * @param {Node} color - Defines the color of the fog.
  26697. * @param {Node} factor - Defines how the fog is factored in the scene.
  26698. */
  26699. const fog = Fn( ( [ color, factor ] ) => {
  26700. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  26701. } );
  26702. // Deprecated
  26703. /**
  26704. * @tsl
  26705. * @function
  26706. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  26707. *
  26708. * @param {Node} color
  26709. * @param {Node} near
  26710. * @param {Node} far
  26711. * @returns {Function}
  26712. */
  26713. function rangeFog( color, near, far ) { // @deprecated, r171
  26714. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  26715. return fog( color, rangeFogFactor( near, far ) );
  26716. }
  26717. /**
  26718. * @tsl
  26719. * @function
  26720. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  26721. *
  26722. * @param {Node} color
  26723. * @param {Node} density
  26724. * @returns {Function}
  26725. */
  26726. function densityFog( color, density ) { // @deprecated, r171
  26727. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  26728. return fog( color, densityFogFactor( density ) );
  26729. }
  26730. let min = null;
  26731. let max = null;
  26732. /**
  26733. * `RangeNode` generates random instanced attribute data in a defined range.
  26734. * An exemplary use case for this utility node is to generate random per-instance
  26735. * colors:
  26736. * ```js
  26737. * const material = new MeshBasicNodeMaterial();
  26738. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  26739. * const mesh = new InstancedMesh( geometry, material, count );
  26740. * ```
  26741. * @augments Node
  26742. */
  26743. class RangeNode extends Node {
  26744. static get type() {
  26745. return 'RangeNode';
  26746. }
  26747. /**
  26748. * Constructs a new range node.
  26749. *
  26750. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26751. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26752. */
  26753. constructor( minNode = float(), maxNode = float() ) {
  26754. super();
  26755. /**
  26756. * A node defining the lower bound of the range.
  26757. *
  26758. * @type {Node<any>}
  26759. * @default float()
  26760. */
  26761. this.minNode = minNode;
  26762. /**
  26763. * A node defining the upper bound of the range.
  26764. *
  26765. * @type {Node<any>}
  26766. * @default float()
  26767. */
  26768. this.maxNode = maxNode;
  26769. }
  26770. /**
  26771. * Returns the vector length which is computed based on the range definition.
  26772. *
  26773. * @param {NodeBuilder} builder - The current node builder.
  26774. * @return {number} The vector length.
  26775. */
  26776. getVectorLength( builder ) {
  26777. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  26778. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  26779. return minLength > maxLength ? minLength : maxLength;
  26780. }
  26781. /**
  26782. * This method is overwritten since the node type is inferred from range definition.
  26783. *
  26784. * @param {NodeBuilder} builder - The current node builder.
  26785. * @return {string} The node type.
  26786. */
  26787. getNodeType( builder ) {
  26788. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  26789. }
  26790. setup( builder ) {
  26791. const object = builder.object;
  26792. let output = null;
  26793. if ( object.count > 1 ) {
  26794. const minValue = this.minNode.value;
  26795. const maxValue = this.maxNode.value;
  26796. const minLength = builder.getTypeLength( getValueType( minValue ) );
  26797. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  26798. min = min || new Vector4();
  26799. max = max || new Vector4();
  26800. min.setScalar( 0 );
  26801. max.setScalar( 0 );
  26802. if ( minLength === 1 ) min.setScalar( minValue );
  26803. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  26804. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  26805. if ( maxLength === 1 ) max.setScalar( maxValue );
  26806. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  26807. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  26808. const stride = 4;
  26809. const length = stride * object.count;
  26810. const array = new Float32Array( length );
  26811. for ( let i = 0; i < length; i ++ ) {
  26812. const index = i % stride;
  26813. const minElementValue = min.getComponent( index );
  26814. const maxElementValue = max.getComponent( index );
  26815. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  26816. }
  26817. const nodeType = this.getNodeType( builder );
  26818. if ( object.count <= 4096 ) {
  26819. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  26820. } else {
  26821. // TODO: Improve anonymous buffer attribute creation removing this part
  26822. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  26823. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  26824. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  26825. }
  26826. } else {
  26827. output = float( 0 );
  26828. }
  26829. return output;
  26830. }
  26831. }
  26832. /**
  26833. * TSL function for creating a range node.
  26834. *
  26835. * @tsl
  26836. * @function
  26837. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26838. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26839. * @returns {RangeNode}
  26840. */
  26841. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  26842. /**
  26843. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  26844. * about the currently running dispatch and/or the device it is running on.
  26845. *
  26846. * This node can only be used with a WebGPU backend.
  26847. *
  26848. * @augments Node
  26849. */
  26850. class ComputeBuiltinNode extends Node {
  26851. static get type() {
  26852. return 'ComputeBuiltinNode';
  26853. }
  26854. /**
  26855. * Constructs a new compute builtin node.
  26856. *
  26857. * @param {string} builtinName - The built-in name.
  26858. * @param {string} nodeType - The node type.
  26859. */
  26860. constructor( builtinName, nodeType ) {
  26861. super( nodeType );
  26862. /**
  26863. * The built-in name.
  26864. *
  26865. * @private
  26866. * @type {string}
  26867. */
  26868. this._builtinName = builtinName;
  26869. }
  26870. /**
  26871. * This method is overwritten since hash is derived from the built-in name.
  26872. *
  26873. * @param {NodeBuilder} builder - The current node builder.
  26874. * @return {string} The hash.
  26875. */
  26876. getHash( builder ) {
  26877. return this.getBuiltinName( builder );
  26878. }
  26879. /**
  26880. * This method is overwritten since the node type is simply derived from `nodeType`..
  26881. *
  26882. * @param {NodeBuilder} builder - The current node builder.
  26883. * @return {string} The node type.
  26884. */
  26885. getNodeType( /*builder*/ ) {
  26886. return this.nodeType;
  26887. }
  26888. /**
  26889. * Sets the builtin name.
  26890. *
  26891. * @param {string} builtinName - The built-in name.
  26892. * @return {ComputeBuiltinNode} A reference to this node.
  26893. */
  26894. setBuiltinName( builtinName ) {
  26895. this._builtinName = builtinName;
  26896. return this;
  26897. }
  26898. /**
  26899. * Returns the builtin name.
  26900. *
  26901. * @param {NodeBuilder} builder - The current node builder.
  26902. * @return {string} The builtin name.
  26903. */
  26904. getBuiltinName( /*builder*/ ) {
  26905. return this._builtinName;
  26906. }
  26907. /**
  26908. * Whether the current node builder has the builtin or not.
  26909. *
  26910. * @param {NodeBuilder} builder - The current node builder.
  26911. * @return {boolean} Whether the builder has the builtin or not.
  26912. */
  26913. hasBuiltin( builder ) {
  26914. return builder.hasBuiltin( this._builtinName );
  26915. }
  26916. generate( builder, output ) {
  26917. const builtinName = this.getBuiltinName( builder );
  26918. const nodeType = this.getNodeType( builder );
  26919. if ( builder.shaderStage === 'compute' ) {
  26920. return builder.format( builtinName, nodeType, output );
  26921. } else {
  26922. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  26923. return builder.generateConst( nodeType );
  26924. }
  26925. }
  26926. serialize( data ) {
  26927. super.serialize( data );
  26928. data.global = this.global;
  26929. data._builtinName = this._builtinName;
  26930. }
  26931. deserialize( data ) {
  26932. super.deserialize( data );
  26933. this.global = data.global;
  26934. this._builtinName = data._builtinName;
  26935. }
  26936. }
  26937. /**
  26938. * TSL function for creating a compute builtin node.
  26939. *
  26940. * @tsl
  26941. * @function
  26942. * @param {string} name - The built-in name.
  26943. * @param {string} nodeType - The node type.
  26944. * @returns {ComputeBuiltinNode}
  26945. */
  26946. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  26947. /**
  26948. * Represents the number of workgroups dispatched by the compute shader.
  26949. * ```js
  26950. * // Run 512 invocations/threads with a workgroup size of 128.
  26951. * const computeFn = Fn(() => {
  26952. *
  26953. * // numWorkgroups.x = 4
  26954. * storageBuffer.element(0).assign(numWorkgroups.x)
  26955. *
  26956. * })().compute(512, [128]);
  26957. *
  26958. * // Run 512 invocations/threads with the default workgroup size of 64.
  26959. * const computeFn = Fn(() => {
  26960. *
  26961. * // numWorkgroups.x = 8
  26962. * storageBuffer.element(0).assign(numWorkgroups.x)
  26963. *
  26964. * })().compute(512);
  26965. * ```
  26966. *
  26967. * @tsl
  26968. * @type {ComputeBuiltinNode<uvec3>}
  26969. */
  26970. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  26971. /**
  26972. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  26973. * ```js
  26974. * // Execute 12 compute threads with a workgroup size of 3.
  26975. * const computeFn = Fn( () => {
  26976. *
  26977. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  26978. *
  26979. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  26980. *
  26981. * } ).Else( () => {
  26982. *
  26983. * storageBuffer.element( instanceIndex ).assign( 0 );
  26984. *
  26985. * } );
  26986. *
  26987. * } )().compute( 12, [ 3 ] );
  26988. *
  26989. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  26990. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  26991. * ```
  26992. *
  26993. * @tsl
  26994. * @type {ComputeBuiltinNode<uvec3>}
  26995. */
  26996. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  26997. /**
  26998. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  26999. *
  27000. * @tsl
  27001. * @type {ComputeBuiltinNode<uvec3>}
  27002. */
  27003. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  27004. /**
  27005. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  27006. *
  27007. * @tsl
  27008. * @type {ComputeBuiltinNode<uvec3>}
  27009. */
  27010. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  27011. /**
  27012. * A device dependent variable that exposes the size of the current invocation's subgroup.
  27013. *
  27014. * @tsl
  27015. * @type {ComputeBuiltinNode<uint>}
  27016. */
  27017. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  27018. /**
  27019. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  27020. *
  27021. * This node can only be used with a WebGPU backend.
  27022. *
  27023. * @augments Node
  27024. */
  27025. class BarrierNode extends Node {
  27026. /**
  27027. * Constructs a new barrier node.
  27028. *
  27029. * @param {string} scope - The scope defines the behavior of the node.
  27030. */
  27031. constructor( scope ) {
  27032. super();
  27033. this.scope = scope;
  27034. }
  27035. generate( builder ) {
  27036. const { scope } = this;
  27037. const { renderer } = builder;
  27038. if ( renderer.backend.isWebGLBackend === true ) {
  27039. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  27040. } else {
  27041. builder.addLineFlowCode( `${scope}Barrier()`, this );
  27042. }
  27043. }
  27044. }
  27045. /**
  27046. * TSL function for creating a barrier node.
  27047. *
  27048. * @tsl
  27049. * @function
  27050. * @param {string} scope - The scope defines the behavior of the node..
  27051. * @returns {BarrierNode}
  27052. */
  27053. const barrier = nodeProxy( BarrierNode );
  27054. /**
  27055. * TSL function for creating a workgroup barrier. All compute shader
  27056. * invocations must wait for each invocation within a workgroup to
  27057. * complete before the barrier can be surpassed.
  27058. *
  27059. * @tsl
  27060. * @function
  27061. * @returns {BarrierNode}
  27062. */
  27063. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  27064. /**
  27065. * TSL function for creating a storage barrier. All invocations must
  27066. * wait for each access to variables within the 'storage' address space
  27067. * to complete before the barrier can be passed.
  27068. *
  27069. * @tsl
  27070. * @function
  27071. * @returns {BarrierNode}
  27072. */
  27073. const storageBarrier = () => barrier( 'storage' ).toStack();
  27074. /**
  27075. * TSL function for creating a texture barrier. All invocations must
  27076. * wait for each access to variables within the 'texture' address space
  27077. * to complete before the barrier can be passed.
  27078. *
  27079. * @tsl
  27080. * @function
  27081. * @returns {BarrierNode}
  27082. */
  27083. const textureBarrier = () => barrier( 'texture' ).toStack();
  27084. /**
  27085. * Represents an element of a 'workgroup' scoped buffer.
  27086. *
  27087. * @augments ArrayElementNode
  27088. */
  27089. class WorkgroupInfoElementNode extends ArrayElementNode {
  27090. /**
  27091. * Constructs a new workgroup info element node.
  27092. *
  27093. * @param {Node} workgroupInfoNode - The workgroup info node.
  27094. * @param {Node} indexNode - The index node that defines the element access.
  27095. */
  27096. constructor( workgroupInfoNode, indexNode ) {
  27097. super( workgroupInfoNode, indexNode );
  27098. /**
  27099. * This flag can be used for type testing.
  27100. *
  27101. * @type {boolean}
  27102. * @readonly
  27103. * @default true
  27104. */
  27105. this.isWorkgroupInfoElementNode = true;
  27106. }
  27107. generate( builder, output ) {
  27108. let snippet;
  27109. const isAssignContext = builder.context.assign;
  27110. snippet = super.generate( builder );
  27111. if ( isAssignContext !== true ) {
  27112. const type = this.getNodeType( builder );
  27113. snippet = builder.format( snippet, type, output );
  27114. }
  27115. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  27116. return snippet;
  27117. }
  27118. }
  27119. /**
  27120. * A node allowing the user to create a 'workgroup' scoped buffer within the
  27121. * context of a compute shader. Typically, workgroup scoped buffers are
  27122. * created to hold data that is transferred from a global storage scope into
  27123. * a local workgroup scope. For invocations within a workgroup, data
  27124. * access speeds on 'workgroup' scoped buffers can be significantly faster
  27125. * than similar access operations on globally accessible storage buffers.
  27126. *
  27127. * This node can only be used with a WebGPU backend.
  27128. *
  27129. * @augments Node
  27130. */
  27131. class WorkgroupInfoNode extends Node {
  27132. /**
  27133. * Constructs a new buffer scoped to type scope.
  27134. *
  27135. * @param {string} scope - TODO.
  27136. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  27137. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  27138. */
  27139. constructor( scope, bufferType, bufferCount = 0 ) {
  27140. super( bufferType );
  27141. /**
  27142. * The buffer type.
  27143. *
  27144. * @type {string}
  27145. */
  27146. this.bufferType = bufferType;
  27147. /**
  27148. * The buffer count.
  27149. *
  27150. * @type {number}
  27151. * @default 0
  27152. */
  27153. this.bufferCount = bufferCount;
  27154. /**
  27155. * This flag can be used for type testing.
  27156. *
  27157. * @type {boolean}
  27158. * @readonly
  27159. * @default true
  27160. */
  27161. this.isWorkgroupInfoNode = true;
  27162. /**
  27163. * The data type of the array buffer.
  27164. *
  27165. * @type {string}
  27166. */
  27167. this.elementType = bufferType;
  27168. /**
  27169. * TODO.
  27170. *
  27171. * @type {string}
  27172. */
  27173. this.scope = scope;
  27174. /**
  27175. * The name of the workgroup scoped buffer.
  27176. *
  27177. * @type {string}
  27178. * @default ''
  27179. */
  27180. this.name = '';
  27181. }
  27182. /**
  27183. * Sets the name of this node.
  27184. *
  27185. * @param {string} name - The name to set.
  27186. * @return {WorkgroupInfoNode} A reference to this node.
  27187. */
  27188. setName( name ) {
  27189. this.name = name;
  27190. return this;
  27191. }
  27192. /**
  27193. * Sets the name/label of this node.
  27194. *
  27195. * @deprecated
  27196. * @param {string} name - The name to set.
  27197. * @return {WorkgroupInfoNode} A reference to this node.
  27198. */
  27199. label( name ) {
  27200. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  27201. return this.setName( name );
  27202. }
  27203. /**
  27204. * Sets the scope of this node.
  27205. *
  27206. * @param {string} scope - The scope to set.
  27207. * @return {WorkgroupInfoNode} A reference to this node.
  27208. */
  27209. setScope( scope ) {
  27210. this.scope = scope;
  27211. return this;
  27212. }
  27213. /**
  27214. * The data type of the array buffer.
  27215. *
  27216. * @return {string} The element type.
  27217. */
  27218. getElementType() {
  27219. return this.elementType;
  27220. }
  27221. /**
  27222. * Overwrites the default implementation since the input type
  27223. * is inferred from the scope.
  27224. *
  27225. * @param {NodeBuilder} builder - The current node builder.
  27226. * @return {string} The input type.
  27227. */
  27228. getInputType( /*builder*/ ) {
  27229. return `${this.scope}Array`;
  27230. }
  27231. /**
  27232. * This method can be used to access elements via an index node.
  27233. *
  27234. * @param {IndexNode} indexNode - indexNode.
  27235. * @return {WorkgroupInfoElementNode} A reference to an element.
  27236. */
  27237. element( indexNode ) {
  27238. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  27239. }
  27240. generate( builder ) {
  27241. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  27242. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  27243. }
  27244. }
  27245. /**
  27246. * TSL function for creating a workgroup info node.
  27247. * Creates a new 'workgroup' scoped array buffer.
  27248. *
  27249. * @tsl
  27250. * @function
  27251. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  27252. * @param {number} [count=0] - The number of elements in the buffer.
  27253. * @returns {WorkgroupInfoNode}
  27254. */
  27255. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  27256. /**
  27257. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  27258. * within a shader. In an atomic function, any modification to an atomic variable will
  27259. * occur as an indivisible step with a defined order relative to other modifications.
  27260. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  27261. * atomic operations will not interfere with each other.
  27262. *
  27263. * This node can only be used with a WebGPU backend.
  27264. *
  27265. * @augments Node
  27266. */
  27267. class AtomicFunctionNode extends Node {
  27268. static get type() {
  27269. return 'AtomicFunctionNode';
  27270. }
  27271. /**
  27272. * Constructs a new atomic function node.
  27273. *
  27274. * @param {string} method - The signature of the atomic function to construct.
  27275. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27276. * @param {Node} valueNode - The value that mutates the atomic variable.
  27277. */
  27278. constructor( method, pointerNode, valueNode ) {
  27279. super( 'uint' );
  27280. /**
  27281. * The signature of the atomic function to construct.
  27282. *
  27283. * @type {string}
  27284. */
  27285. this.method = method;
  27286. /**
  27287. * An atomic variable or element of an atomic buffer.
  27288. *
  27289. * @type {Node}
  27290. */
  27291. this.pointerNode = pointerNode;
  27292. /**
  27293. * A value that modifies the atomic variable.
  27294. *
  27295. * @type {Node}
  27296. */
  27297. this.valueNode = valueNode;
  27298. /**
  27299. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  27300. *
  27301. * @type {boolean}
  27302. * @default true
  27303. */
  27304. this.parents = true;
  27305. }
  27306. /**
  27307. * Overwrites the default implementation to return the type of
  27308. * the pointer node.
  27309. *
  27310. * @param {NodeBuilder} builder - The current node builder.
  27311. * @return {string} The input type.
  27312. */
  27313. getInputType( builder ) {
  27314. return this.pointerNode.getNodeType( builder );
  27315. }
  27316. /**
  27317. * Overwritten since the node type is inferred from the input type.
  27318. *
  27319. * @param {NodeBuilder} builder - The current node builder.
  27320. * @return {string} The node type.
  27321. */
  27322. getNodeType( builder ) {
  27323. return this.getInputType( builder );
  27324. }
  27325. generate( builder ) {
  27326. const properties = builder.getNodeProperties( this );
  27327. const parents = properties.parents;
  27328. const method = this.method;
  27329. const type = this.getNodeType( builder );
  27330. const inputType = this.getInputType( builder );
  27331. const a = this.pointerNode;
  27332. const b = this.valueNode;
  27333. const params = [];
  27334. params.push( `&${ a.build( builder, inputType ) }` );
  27335. if ( b !== null ) {
  27336. params.push( b.build( builder, inputType ) );
  27337. }
  27338. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  27339. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  27340. if ( isVoid ) {
  27341. builder.addLineFlowCode( methodSnippet, this );
  27342. } else {
  27343. if ( properties.constNode === undefined ) {
  27344. properties.constNode = expression( methodSnippet, type ).toConst();
  27345. }
  27346. return properties.constNode.build( builder );
  27347. }
  27348. }
  27349. }
  27350. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  27351. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  27352. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  27353. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  27354. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  27355. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  27356. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  27357. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  27358. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  27359. /**
  27360. * TSL function for creating an atomic function node.
  27361. *
  27362. * @tsl
  27363. * @function
  27364. * @param {string} method - The signature of the atomic function to construct.
  27365. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27366. * @param {Node} valueNode - The value that mutates the atomic variable.
  27367. * @returns {AtomicFunctionNode}
  27368. */
  27369. const atomicNode = nodeProxy( AtomicFunctionNode );
  27370. /**
  27371. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  27372. *
  27373. * @tsl
  27374. * @function
  27375. * @param {string} method - The signature of the atomic function to construct.
  27376. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27377. * @param {Node} valueNode - The value that mutates the atomic variable.
  27378. * @returns {AtomicFunctionNode}
  27379. */
  27380. const atomicFunc = ( method, pointerNode, valueNode ) => {
  27381. return atomicNode( method, pointerNode, valueNode ).toStack();
  27382. };
  27383. /**
  27384. * Loads the value stored in the atomic variable.
  27385. *
  27386. * @tsl
  27387. * @function
  27388. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27389. * @returns {AtomicFunctionNode}
  27390. */
  27391. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  27392. /**
  27393. * Stores a value in the atomic variable.
  27394. *
  27395. * @tsl
  27396. * @function
  27397. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27398. * @param {Node} valueNode - The value that mutates the atomic variable.
  27399. * @returns {AtomicFunctionNode}
  27400. */
  27401. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  27402. /**
  27403. * Increments the value stored in the atomic variable.
  27404. *
  27405. * @tsl
  27406. * @function
  27407. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27408. * @param {Node} valueNode - The value that mutates the atomic variable.
  27409. * @returns {AtomicFunctionNode}
  27410. */
  27411. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  27412. /**
  27413. * Decrements the value stored in the atomic variable.
  27414. *
  27415. * @tsl
  27416. * @function
  27417. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27418. * @param {Node} valueNode - The value that mutates the atomic variable.
  27419. * @returns {AtomicFunctionNode}
  27420. */
  27421. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  27422. /**
  27423. * Stores in an atomic variable the maximum between its current value and a parameter.
  27424. *
  27425. * @tsl
  27426. * @function
  27427. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27428. * @param {Node} valueNode - The value that mutates the atomic variable.
  27429. * @returns {AtomicFunctionNode}
  27430. */
  27431. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  27432. /**
  27433. * Stores in an atomic variable the minimum between its current value and a parameter.
  27434. *
  27435. * @tsl
  27436. * @function
  27437. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27438. * @param {Node} valueNode - The value that mutates the atomic variable.
  27439. * @returns {AtomicFunctionNode}
  27440. */
  27441. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  27442. /**
  27443. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  27444. *
  27445. * @tsl
  27446. * @function
  27447. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27448. * @param {Node} valueNode - The value that mutates the atomic variable.
  27449. * @returns {AtomicFunctionNode}
  27450. */
  27451. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  27452. /**
  27453. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  27454. *
  27455. * @tsl
  27456. * @function
  27457. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27458. * @param {Node} valueNode - The value that mutates the atomic variable.
  27459. * @returns {AtomicFunctionNode}
  27460. */
  27461. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  27462. /**
  27463. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  27464. *
  27465. * @tsl
  27466. * @function
  27467. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27468. * @param {Node} valueNode - The value that mutates the atomic variable.
  27469. * @returns {AtomicFunctionNode}
  27470. */
  27471. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  27472. let uniformsLib;
  27473. function getLightData( light ) {
  27474. uniformsLib = uniformsLib || new WeakMap();
  27475. let uniforms = uniformsLib.get( light );
  27476. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  27477. return uniforms;
  27478. }
  27479. /**
  27480. * TSL function for getting a shadow matrix uniform node for the given light.
  27481. *
  27482. * @tsl
  27483. * @function
  27484. * @param {Light} light -The light source.
  27485. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  27486. */
  27487. function lightShadowMatrix( light ) {
  27488. const data = getLightData( light );
  27489. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  27490. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  27491. light.shadow.updateMatrices( light );
  27492. }
  27493. return light.shadow.matrix;
  27494. } ) );
  27495. }
  27496. /**
  27497. * TSL function for getting projected uv coordinates for the given light.
  27498. * Relevant when using maps with spot lights.
  27499. *
  27500. * @tsl
  27501. * @function
  27502. * @param {Light} light -The light source.
  27503. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  27504. * @returns {Node<vec3>} The projected uvs.
  27505. */
  27506. function lightProjectionUV( light, position = positionWorld ) {
  27507. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  27508. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  27509. return projectionUV;
  27510. }
  27511. /**
  27512. * TSL function for getting the position in world space for the given light.
  27513. *
  27514. * @tsl
  27515. * @function
  27516. * @param {Light} light -The light source.
  27517. * @returns {UniformNode<vec3>} The light's position in world space.
  27518. */
  27519. function lightPosition( light ) {
  27520. const data = getLightData( light );
  27521. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  27522. }
  27523. /**
  27524. * TSL function for getting the light target position in world space for the given light.
  27525. *
  27526. * @tsl
  27527. * @function
  27528. * @param {Light} light -The light source.
  27529. * @returns {UniformNode<vec3>} The light target position in world space.
  27530. */
  27531. function lightTargetPosition( light ) {
  27532. const data = getLightData( light );
  27533. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  27534. }
  27535. /**
  27536. * TSL function for getting the position in view space for the given light.
  27537. *
  27538. * @tsl
  27539. * @function
  27540. * @param {Light} light - The light source.
  27541. * @returns {UniformNode<vec3>} The light's position in view space.
  27542. */
  27543. function lightViewPosition( light ) {
  27544. const data = getLightData( light );
  27545. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  27546. self.value = self.value || new Vector3();
  27547. self.value.setFromMatrixPosition( light.matrixWorld );
  27548. self.value.applyMatrix4( camera.matrixWorldInverse );
  27549. } ) );
  27550. }
  27551. /**
  27552. * TSL function for getting the light target direction for the given light.
  27553. *
  27554. * @tsl
  27555. * @function
  27556. * @param {Light} light -The light source.
  27557. * @returns {Node<vec3>} The light's target direction.
  27558. */
  27559. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  27560. const sortLights = ( lights ) => {
  27561. return lights.sort( ( a, b ) => a.id - b.id );
  27562. };
  27563. const getLightNodeById = ( id, lightNodes ) => {
  27564. for ( const lightNode of lightNodes ) {
  27565. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  27566. return lightNode;
  27567. }
  27568. }
  27569. return null;
  27570. };
  27571. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  27572. const _hashData = [];
  27573. /**
  27574. * This node represents the scene's lighting and manages the lighting model's life cycle
  27575. * for the current build 3D object. It is responsible for computing the total outgoing
  27576. * light in a given lighting context.
  27577. *
  27578. * @augments Node
  27579. */
  27580. class LightsNode extends Node {
  27581. static get type() {
  27582. return 'LightsNode';
  27583. }
  27584. /**
  27585. * Constructs a new lights node.
  27586. */
  27587. constructor() {
  27588. super( 'vec3' );
  27589. /**
  27590. * A node representing the total diffuse light.
  27591. *
  27592. * @type {Node<vec3>}
  27593. */
  27594. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  27595. /**
  27596. * A node representing the total specular light.
  27597. *
  27598. * @type {Node<vec3>}
  27599. */
  27600. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  27601. /**
  27602. * A node representing the outgoing light.
  27603. *
  27604. * @type {Node<vec3>}
  27605. */
  27606. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  27607. /**
  27608. * An array representing the lights in the scene.
  27609. *
  27610. * @private
  27611. * @type {Array<Light>}
  27612. */
  27613. this._lights = [];
  27614. /**
  27615. * For each light in the scene, this node will create a
  27616. * corresponding light node.
  27617. *
  27618. * @private
  27619. * @type {?Array<LightingNode>}
  27620. * @default null
  27621. */
  27622. this._lightNodes = null;
  27623. /**
  27624. * A hash for identifying the current light nodes setup.
  27625. *
  27626. * @private
  27627. * @type {?string}
  27628. * @default null
  27629. */
  27630. this._lightNodesHash = null;
  27631. /**
  27632. * `LightsNode` sets this property to `true` by default.
  27633. *
  27634. * @type {boolean}
  27635. * @default true
  27636. */
  27637. this.global = true;
  27638. }
  27639. /**
  27640. * Overwrites the default {@link Node#customCacheKey} implementation by including
  27641. * light data into the cache key.
  27642. *
  27643. * @return {number} The custom cache key.
  27644. */
  27645. customCacheKey() {
  27646. const lights = this._lights;
  27647. for ( let i = 0; i < lights.length; i ++ ) {
  27648. const light = lights[ i ];
  27649. _hashData.push( light.id );
  27650. _hashData.push( light.castShadow ? 1 : 0 );
  27651. if ( light.isSpotLight === true ) {
  27652. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  27653. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  27654. _hashData.push( hashMap, hashColorNode );
  27655. }
  27656. }
  27657. const cacheKey = hashArray( _hashData );
  27658. _hashData.length = 0;
  27659. return cacheKey;
  27660. }
  27661. /**
  27662. * Computes a hash value for identifying the current light nodes setup.
  27663. *
  27664. * @param {NodeBuilder} builder - A reference to the current node builder.
  27665. * @return {string} The computed hash.
  27666. */
  27667. getHash( builder ) {
  27668. if ( this._lightNodesHash === null ) {
  27669. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27670. const hash = [];
  27671. for ( const lightNode of this._lightNodes ) {
  27672. hash.push( lightNode.getSelf().getHash() );
  27673. }
  27674. this._lightNodesHash = 'lights-' + hash.join( ',' );
  27675. }
  27676. return this._lightNodesHash;
  27677. }
  27678. analyze( builder ) {
  27679. const properties = builder.getNodeProperties( this );
  27680. for ( const node of properties.nodes ) {
  27681. node.build( builder );
  27682. }
  27683. properties.outputNode.build( builder );
  27684. }
  27685. /**
  27686. * Creates lighting nodes for each scene light. This makes it possible to further
  27687. * process lights in the node system.
  27688. *
  27689. * @param {NodeBuilder} builder - A reference to the current node builder.
  27690. */
  27691. setupLightsNode( builder ) {
  27692. const lightNodes = [];
  27693. const previousLightNodes = this._lightNodes;
  27694. const lights = sortLights( this._lights );
  27695. const nodeLibrary = builder.renderer.library;
  27696. for ( const light of lights ) {
  27697. if ( light.isNode ) {
  27698. lightNodes.push( nodeObject( light ) );
  27699. } else {
  27700. let lightNode = null;
  27701. if ( previousLightNodes !== null ) {
  27702. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  27703. }
  27704. if ( lightNode === null ) {
  27705. // find the corresponding node type for a given light
  27706. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  27707. if ( lightNodeClass === null ) {
  27708. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  27709. continue;
  27710. }
  27711. let lightNode = null;
  27712. if ( ! _lightsNodeRef.has( light ) ) {
  27713. lightNode = nodeObject( new lightNodeClass( light ) );
  27714. _lightsNodeRef.set( light, lightNode );
  27715. } else {
  27716. lightNode = _lightsNodeRef.get( light );
  27717. }
  27718. lightNodes.push( lightNode );
  27719. }
  27720. }
  27721. }
  27722. this._lightNodes = lightNodes;
  27723. }
  27724. /**
  27725. * Sets up a direct light in the lighting model.
  27726. *
  27727. * @param {Object} builder - The builder object containing the context and stack.
  27728. * @param {Object} lightNode - The light node.
  27729. * @param {Object} lightData - The light object containing color and direction properties.
  27730. */
  27731. setupDirectLight( builder, lightNode, lightData ) {
  27732. const { lightingModel, reflectedLight } = builder.context;
  27733. lightingModel.direct( {
  27734. ...lightData,
  27735. lightNode,
  27736. reflectedLight
  27737. }, builder );
  27738. }
  27739. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  27740. const { lightingModel, reflectedLight } = builder.context;
  27741. lightingModel.directRectArea( {
  27742. ...lightData,
  27743. lightNode,
  27744. reflectedLight
  27745. }, builder );
  27746. }
  27747. /**
  27748. * Setups the internal lights by building all respective
  27749. * light nodes.
  27750. *
  27751. * @param {NodeBuilder} builder - A reference to the current node builder.
  27752. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  27753. */
  27754. setupLights( builder, lightNodes ) {
  27755. for ( const lightNode of lightNodes ) {
  27756. lightNode.build( builder );
  27757. }
  27758. }
  27759. getLightNodes( builder ) {
  27760. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27761. return this._lightNodes;
  27762. }
  27763. /**
  27764. * The implementation makes sure that for each light in the scene
  27765. * there is a corresponding light node. By building the light nodes
  27766. * and evaluating the lighting model the outgoing light is computed.
  27767. *
  27768. * @param {NodeBuilder} builder - A reference to the current node builder.
  27769. * @return {Node<vec3>} A node representing the outgoing light.
  27770. */
  27771. setup( builder ) {
  27772. const currentLightsNode = builder.lightsNode;
  27773. builder.lightsNode = this;
  27774. //
  27775. let outgoingLightNode = this.outgoingLightNode;
  27776. const context = builder.context;
  27777. const lightingModel = context.lightingModel;
  27778. const properties = builder.getNodeProperties( this );
  27779. if ( lightingModel ) {
  27780. const { totalDiffuseNode, totalSpecularNode } = this;
  27781. context.outgoingLight = outgoingLightNode;
  27782. const stack = builder.addStack();
  27783. //
  27784. properties.nodes = stack.nodes;
  27785. //
  27786. lightingModel.start( builder );
  27787. //
  27788. const { backdrop, backdropAlpha } = context;
  27789. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  27790. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  27791. if ( backdrop !== null ) {
  27792. if ( backdropAlpha !== null ) {
  27793. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  27794. } else {
  27795. totalDiffuse = vec3( backdrop );
  27796. }
  27797. context.material.transparent = true;
  27798. }
  27799. totalDiffuseNode.assign( totalDiffuse );
  27800. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  27801. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  27802. //
  27803. lightingModel.finish( builder );
  27804. //
  27805. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  27806. } else {
  27807. properties.nodes = [];
  27808. }
  27809. //
  27810. builder.lightsNode = currentLightsNode;
  27811. return outgoingLightNode;
  27812. }
  27813. /**
  27814. * Configures this node with an array of lights.
  27815. *
  27816. * @param {Array<Light>} lights - An array of lights.
  27817. * @return {LightsNode} A reference to this node.
  27818. */
  27819. setLights( lights ) {
  27820. this._lights = lights;
  27821. this._lightNodes = null;
  27822. this._lightNodesHash = null;
  27823. return this;
  27824. }
  27825. /**
  27826. * Returns an array of the scene's lights.
  27827. *
  27828. * @return {Array<Light>} The scene's lights.
  27829. */
  27830. getLights() {
  27831. return this._lights;
  27832. }
  27833. /**
  27834. * Whether the scene has lights or not.
  27835. *
  27836. * @type {boolean}
  27837. */
  27838. get hasLights() {
  27839. return this._lights.length > 0;
  27840. }
  27841. }
  27842. /**
  27843. * TSL function for creating an instance of `LightsNode` and configuring
  27844. * it with the given array of lights.
  27845. *
  27846. * @tsl
  27847. * @function
  27848. * @param {Array<Light>} lights - An array of lights.
  27849. * @return {LightsNode} The created lights node.
  27850. */
  27851. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  27852. /**
  27853. * Base class for all shadow nodes.
  27854. *
  27855. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  27856. * Lighting nodes might share the same shadow node type or use specific ones depending on
  27857. * their requirements.
  27858. *
  27859. * @augments Node
  27860. */
  27861. class ShadowBaseNode extends Node {
  27862. static get type() {
  27863. return 'ShadowBaseNode';
  27864. }
  27865. /**
  27866. * Constructs a new shadow base node.
  27867. *
  27868. * @param {Light} light - The shadow casting light.
  27869. */
  27870. constructor( light ) {
  27871. super();
  27872. /**
  27873. * The shadow casting light.
  27874. *
  27875. * @type {Light}
  27876. */
  27877. this.light = light;
  27878. /**
  27879. * Overwritten since shadows are updated by default per render.
  27880. *
  27881. * @type {string}
  27882. * @default 'render'
  27883. */
  27884. this.updateBeforeType = NodeUpdateType.RENDER;
  27885. /**
  27886. * This flag can be used for type testing.
  27887. *
  27888. * @type {boolean}
  27889. * @readonly
  27890. * @default true
  27891. */
  27892. this.isShadowBaseNode = true;
  27893. }
  27894. /**
  27895. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  27896. *
  27897. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  27898. */
  27899. setupShadowPosition( { context, material } ) {
  27900. // Use assign inside an Fn()
  27901. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  27902. }
  27903. }
  27904. /**
  27905. * TSL object that represents the vertex position in world space during the shadow pass.
  27906. *
  27907. * @tsl
  27908. * @type {Node<vec3>}
  27909. */
  27910. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  27911. /**
  27912. * Saves the state of the given renderer and stores it into the given state object.
  27913. *
  27914. * If not state object is provided, the function creates one.
  27915. *
  27916. * @function
  27917. * @param {Renderer} renderer - The renderer.
  27918. * @param {Object} [state={}] - The state.
  27919. * @return {Object} The state.
  27920. */
  27921. function saveRendererState( renderer, state = {} ) {
  27922. state.toneMapping = renderer.toneMapping;
  27923. state.toneMappingExposure = renderer.toneMappingExposure;
  27924. state.outputColorSpace = renderer.outputColorSpace;
  27925. state.renderTarget = renderer.getRenderTarget();
  27926. state.activeCubeFace = renderer.getActiveCubeFace();
  27927. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  27928. state.renderObjectFunction = renderer.getRenderObjectFunction();
  27929. state.pixelRatio = renderer.getPixelRatio();
  27930. state.mrt = renderer.getMRT();
  27931. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  27932. state.clearAlpha = renderer.getClearAlpha();
  27933. state.autoClear = renderer.autoClear;
  27934. state.scissorTest = renderer.getScissorTest();
  27935. return state;
  27936. }
  27937. /**
  27938. * Saves the state of the given renderer and stores it into the given state object.
  27939. * Besides, the function also resets the state of the renderer to its default values.
  27940. *
  27941. * If not state object is provided, the function creates one.
  27942. *
  27943. * @function
  27944. * @param {Renderer} renderer - The renderer.
  27945. * @param {Object} [state={}] - The state.
  27946. * @return {Object} The state.
  27947. */
  27948. function resetRendererState( renderer, state ) {
  27949. state = saveRendererState( renderer, state );
  27950. renderer.setMRT( null );
  27951. renderer.setRenderObjectFunction( null );
  27952. renderer.setClearColor( 0x000000, 1 );
  27953. renderer.autoClear = true;
  27954. return state;
  27955. }
  27956. /**
  27957. * Restores the state of the given renderer from the given state object.
  27958. *
  27959. * @function
  27960. * @param {Renderer} renderer - The renderer.
  27961. * @param {Object} state - The state to restore.
  27962. */
  27963. function restoreRendererState( renderer, state ) {
  27964. renderer.toneMapping = state.toneMapping;
  27965. renderer.toneMappingExposure = state.toneMappingExposure;
  27966. renderer.outputColorSpace = state.outputColorSpace;
  27967. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  27968. renderer.setRenderObjectFunction( state.renderObjectFunction );
  27969. renderer.setPixelRatio( state.pixelRatio );
  27970. renderer.setMRT( state.mrt );
  27971. renderer.setClearColor( state.clearColor, state.clearAlpha );
  27972. renderer.autoClear = state.autoClear;
  27973. renderer.setScissorTest( state.scissorTest );
  27974. }
  27975. /**
  27976. * Saves the state of the given scene and stores it into the given state object.
  27977. *
  27978. * If not state object is provided, the function creates one.
  27979. *
  27980. * @function
  27981. * @param {Scene} scene - The scene.
  27982. * @param {Object} [state={}] - The state.
  27983. * @return {Object} The state.
  27984. */
  27985. function saveSceneState( scene, state = {} ) {
  27986. state.background = scene.background;
  27987. state.backgroundNode = scene.backgroundNode;
  27988. state.overrideMaterial = scene.overrideMaterial;
  27989. return state;
  27990. }
  27991. /**
  27992. * Saves the state of the given scene and stores it into the given state object.
  27993. * Besides, the function also resets the state of the scene to its default values.
  27994. *
  27995. * If not state object is provided, the function creates one.
  27996. *
  27997. * @function
  27998. * @param {Scene} scene - The scene.
  27999. * @param {Object} [state={}] - The state.
  28000. * @return {Object} The state.
  28001. */
  28002. function resetSceneState( scene, state ) {
  28003. state = saveSceneState( scene, state );
  28004. scene.background = null;
  28005. scene.backgroundNode = null;
  28006. scene.overrideMaterial = null;
  28007. return state;
  28008. }
  28009. /**
  28010. * Restores the state of the given scene from the given state object.
  28011. *
  28012. * @function
  28013. * @param {Scene} scene - The scene.
  28014. * @param {Object} state - The state to restore.
  28015. */
  28016. function restoreSceneState( scene, state ) {
  28017. scene.background = state.background;
  28018. scene.backgroundNode = state.backgroundNode;
  28019. scene.overrideMaterial = state.overrideMaterial;
  28020. }
  28021. /**
  28022. * Saves the state of the given renderer and scene and stores it into the given state object.
  28023. *
  28024. * If not state object is provided, the function creates one.
  28025. *
  28026. * @function
  28027. * @param {Renderer} renderer - The renderer.
  28028. * @param {Scene} scene - The scene.
  28029. * @param {Object} [state={}] - The state.
  28030. * @return {Object} The state.
  28031. */
  28032. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  28033. state = saveRendererState( renderer, state );
  28034. state = saveSceneState( scene, state );
  28035. return state;
  28036. }
  28037. /**
  28038. * Saves the state of the given renderer and scene and stores it into the given state object.
  28039. * Besides, the function also resets the state of the renderer and scene to its default values.
  28040. *
  28041. * If not state object is provided, the function creates one.
  28042. *
  28043. * @function
  28044. * @param {Renderer} renderer - The renderer.
  28045. * @param {Scene} scene - The scene.
  28046. * @param {Object} [state={}] - The state.
  28047. * @return {Object} The state.
  28048. */
  28049. function resetRendererAndSceneState( renderer, scene, state ) {
  28050. state = resetRendererState( renderer, state );
  28051. state = resetSceneState( scene, state );
  28052. return state;
  28053. }
  28054. /**
  28055. * Restores the state of the given renderer and scene from the given state object.
  28056. *
  28057. * @function
  28058. * @param {Renderer} renderer - The renderer.
  28059. * @param {Scene} scene - The scene.
  28060. * @param {Object} state - The state to restore.
  28061. */
  28062. function restoreRendererAndSceneState( renderer, scene, state ) {
  28063. restoreRendererState( renderer, state );
  28064. restoreSceneState( scene, state );
  28065. }
  28066. var RendererUtils = /*#__PURE__*/Object.freeze({
  28067. __proto__: null,
  28068. resetRendererAndSceneState: resetRendererAndSceneState,
  28069. resetRendererState: resetRendererState,
  28070. resetSceneState: resetSceneState,
  28071. restoreRendererAndSceneState: restoreRendererAndSceneState,
  28072. restoreRendererState: restoreRendererState,
  28073. restoreSceneState: restoreSceneState,
  28074. saveRendererAndSceneState: saveRendererAndSceneState,
  28075. saveRendererState: saveRendererState,
  28076. saveSceneState: saveSceneState
  28077. });
  28078. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  28079. /**
  28080. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  28081. * with a binary `[0,1]` result.
  28082. *
  28083. * @method
  28084. * @param {Object} inputs - The input parameter object.
  28085. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28086. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28087. * @return {Node<float>} The filtering result.
  28088. */
  28089. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  28090. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  28091. if ( depthTexture.isArrayTexture ) {
  28092. basic = basic.depth( depthLayer );
  28093. }
  28094. return basic.compare( shadowCoord.z );
  28095. } );
  28096. /**
  28097. * A shadow filtering function performing PCF filtering.
  28098. *
  28099. * @method
  28100. * @param {Object} inputs - The input parameter object.
  28101. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28102. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28103. * @param {LightShadow} inputs.shadow - The light shadow.
  28104. * @return {Node<float>} The filtering result.
  28105. */
  28106. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  28107. const depthCompare = ( uv, compare ) => {
  28108. let depth = texture( depthTexture, uv );
  28109. if ( depthTexture.isArrayTexture ) {
  28110. depth = depth.depth( depthLayer );
  28111. }
  28112. return depth.compare( compare );
  28113. };
  28114. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28115. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28116. const texelSize = vec2( 1 ).div( mapSize );
  28117. const dx0 = texelSize.x.negate().mul( radius );
  28118. const dy0 = texelSize.y.negate().mul( radius );
  28119. const dx1 = texelSize.x.mul( radius );
  28120. const dy1 = texelSize.y.mul( radius );
  28121. const dx2 = dx0.div( 2 );
  28122. const dy2 = dy0.div( 2 );
  28123. const dx3 = dx1.div( 2 );
  28124. const dy3 = dy1.div( 2 );
  28125. return add(
  28126. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  28127. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  28128. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  28129. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  28130. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  28131. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  28132. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  28133. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  28134. depthCompare( shadowCoord.xy, shadowCoord.z ),
  28135. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  28136. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  28137. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  28138. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  28139. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  28140. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  28141. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  28142. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  28143. ).mul( 1 / 17 );
  28144. } );
  28145. /**
  28146. * A shadow filtering function performing PCF soft filtering.
  28147. *
  28148. * @method
  28149. * @param {Object} inputs - The input parameter object.
  28150. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28151. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28152. * @param {LightShadow} inputs.shadow - The light shadow.
  28153. * @return {Node<float>} The filtering result.
  28154. */
  28155. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  28156. const depthCompare = ( uv, compare ) => {
  28157. let depth = texture( depthTexture, uv );
  28158. if ( depthTexture.isArrayTexture ) {
  28159. depth = depth.depth( depthLayer );
  28160. }
  28161. return depth.compare( compare );
  28162. };
  28163. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28164. const texelSize = vec2( 1 ).div( mapSize );
  28165. const dx = texelSize.x;
  28166. const dy = texelSize.y;
  28167. const uv = shadowCoord.xy;
  28168. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  28169. uv.subAssign( f.mul( texelSize ) );
  28170. return add(
  28171. depthCompare( uv, shadowCoord.z ),
  28172. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  28173. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  28174. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  28175. mix(
  28176. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  28177. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  28178. f.x
  28179. ),
  28180. mix(
  28181. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  28182. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  28183. f.x
  28184. ),
  28185. mix(
  28186. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  28187. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  28188. f.y
  28189. ),
  28190. mix(
  28191. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  28192. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  28193. f.y
  28194. ),
  28195. mix(
  28196. mix(
  28197. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  28198. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  28199. f.x
  28200. ),
  28201. mix(
  28202. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  28203. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  28204. f.x
  28205. ),
  28206. f.y
  28207. )
  28208. ).mul( 1 / 9 );
  28209. } );
  28210. /**
  28211. * A shadow filtering function performing VSM filtering.
  28212. *
  28213. * @method
  28214. * @param {Object} inputs - The input parameter object.
  28215. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28216. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28217. * @return {Node<float>} The filtering result.
  28218. */
  28219. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  28220. const occlusion = float( 1 ).toVar();
  28221. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  28222. if ( depthTexture.isArrayTexture ) {
  28223. distribution = distribution.depth( depthLayer );
  28224. }
  28225. distribution = distribution.rg;
  28226. const hardShadow = step( shadowCoord.z, distribution.x );
  28227. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  28228. const distance = shadowCoord.z.sub( distribution.x );
  28229. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  28230. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  28231. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  28232. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  28233. } );
  28234. return occlusion;
  28235. } );
  28236. //
  28237. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  28238. let dist = positionWorld.sub( position ).length();
  28239. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  28240. dist = dist.saturate(); // clamp to [ 0, 1 ]
  28241. return dist;
  28242. } );
  28243. const linearShadowDistance = ( light ) => {
  28244. const camera = light.shadow.camera;
  28245. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  28246. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  28247. const referencePosition = objectPosition( light );
  28248. return linearDistance( referencePosition, nearDistance, farDistance );
  28249. };
  28250. /**
  28251. * Retrieves or creates a shadow material for the given light source.
  28252. *
  28253. * This function checks if a shadow material already exists for the provided light.
  28254. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  28255. * in the `shadowMaterialLib` for future use.
  28256. *
  28257. * @param {Light} light - The light source for which the shadow material is needed.
  28258. * If the light is a point light, a depth node is calculated
  28259. * using the linear shadow distance.
  28260. * @returns {NodeMaterial} The shadow material associated with the given light.
  28261. */
  28262. const getShadowMaterial = ( light ) => {
  28263. let material = shadowMaterialLib.get( light );
  28264. if ( material === undefined ) {
  28265. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  28266. material = new NodeMaterial();
  28267. material.colorNode = vec4( 0, 0, 0, 1 );
  28268. material.depthNode = depthNode;
  28269. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  28270. material.name = 'ShadowMaterial';
  28271. material.fog = false;
  28272. shadowMaterialLib.set( light, material );
  28273. }
  28274. return material;
  28275. };
  28276. //
  28277. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  28278. const _shadowRenderObjectKeys = [];
  28279. /**
  28280. * Creates a function to render shadow objects in a scene.
  28281. *
  28282. * @param {Renderer} renderer - The renderer.
  28283. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  28284. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  28285. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  28286. * @return {Function} A function that renders shadow objects.
  28287. *
  28288. * The returned function has the following parameters:
  28289. * @param {Object3D} object - The 3D object to render.
  28290. * @param {Scene} scene - The scene containing the object.
  28291. * @param {Camera} _camera - The camera used for rendering.
  28292. * @param {BufferGeometry} geometry - The geometry of the object.
  28293. * @param {Material} material - The material of the object.
  28294. * @param {Group} group - The group the object belongs to.
  28295. * @param {...any} params - Additional parameters for rendering.
  28296. */
  28297. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  28298. _shadowRenderObjectKeys[ 0 ] = renderer;
  28299. _shadowRenderObjectKeys[ 1 ] = shadow;
  28300. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  28301. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  28302. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  28303. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  28304. if ( useVelocity ) {
  28305. getDataFromObject( object ).useVelocity = true;
  28306. }
  28307. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  28308. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  28309. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  28310. }
  28311. };
  28312. renderObjectFunction.shadowType = shadowType;
  28313. renderObjectFunction.useVelocity = useVelocity;
  28314. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  28315. }
  28316. _shadowRenderObjectKeys[ 0 ] = null;
  28317. _shadowRenderObjectKeys[ 1 ] = null;
  28318. return renderObjectFunction;
  28319. };
  28320. /**
  28321. * Represents the shader code for the first VSM render pass.
  28322. *
  28323. * @method
  28324. * @param {Object} inputs - The input parameter object.
  28325. * @param {Node<float>} inputs.samples - The number of samples
  28326. * @param {Node<float>} inputs.radius - The radius.
  28327. * @param {Node<float>} inputs.size - The size.
  28328. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  28329. * @return {Node<vec2>} The VSM output.
  28330. */
  28331. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  28332. const mean = float( 0 ).toVar( 'meanVertical' );
  28333. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  28334. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  28335. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  28336. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  28337. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  28338. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  28339. if ( shadowPass.value.isArrayTexture ) {
  28340. depth = depth.depth( depthLayer );
  28341. }
  28342. depth = depth.x;
  28343. mean.addAssign( depth );
  28344. squaredMean.addAssign( depth.mul( depth ) );
  28345. } );
  28346. mean.divAssign( samples );
  28347. squaredMean.divAssign( samples );
  28348. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  28349. return vec2( mean, std_dev );
  28350. } );
  28351. /**
  28352. * Represents the shader code for the second VSM render pass.
  28353. *
  28354. * @method
  28355. * @param {Object} inputs - The input parameter object.
  28356. * @param {Node<float>} inputs.samples - The number of samples
  28357. * @param {Node<float>} inputs.radius - The radius.
  28358. * @param {Node<float>} inputs.size - The size.
  28359. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  28360. * @return {Node<vec2>} The VSM output.
  28361. */
  28362. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  28363. const mean = float( 0 ).toVar( 'meanHorizontal' );
  28364. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  28365. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  28366. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  28367. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  28368. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  28369. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  28370. if ( shadowPass.value.isArrayTexture ) {
  28371. distribution = distribution.depth( depthLayer );
  28372. }
  28373. mean.addAssign( distribution.x );
  28374. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  28375. } );
  28376. mean.divAssign( samples );
  28377. squaredMean.divAssign( samples );
  28378. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  28379. return vec2( mean, std_dev );
  28380. } );
  28381. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  28382. //
  28383. let _rendererState;
  28384. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  28385. /**
  28386. * Represents the default shadow implementation for lighting nodes.
  28387. *
  28388. * @augments ShadowBaseNode
  28389. */
  28390. class ShadowNode extends ShadowBaseNode {
  28391. static get type() {
  28392. return 'ShadowNode';
  28393. }
  28394. /**
  28395. * Constructs a new shadow node.
  28396. *
  28397. * @param {Light} light - The shadow casting light.
  28398. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  28399. */
  28400. constructor( light, shadow = null ) {
  28401. super( light );
  28402. /**
  28403. * The light shadow which defines the properties light's
  28404. * shadow.
  28405. *
  28406. * @type {?LightShadow}
  28407. * @default null
  28408. */
  28409. this.shadow = shadow || light.shadow;
  28410. /**
  28411. * A reference to the shadow map which is a render target.
  28412. *
  28413. * @type {?RenderTarget}
  28414. * @default null
  28415. */
  28416. this.shadowMap = null;
  28417. /**
  28418. * Only relevant for VSM shadows. Render target for the
  28419. * first VSM render pass.
  28420. *
  28421. * @type {?RenderTarget}
  28422. * @default null
  28423. */
  28424. this.vsmShadowMapVertical = null;
  28425. /**
  28426. * Only relevant for VSM shadows. Render target for the
  28427. * second VSM render pass.
  28428. *
  28429. * @type {?RenderTarget}
  28430. * @default null
  28431. */
  28432. this.vsmShadowMapHorizontal = null;
  28433. /**
  28434. * Only relevant for VSM shadows. Node material which
  28435. * is used to render the first VSM pass.
  28436. *
  28437. * @type {?NodeMaterial}
  28438. * @default null
  28439. */
  28440. this.vsmMaterialVertical = null;
  28441. /**
  28442. * Only relevant for VSM shadows. Node material which
  28443. * is used to render the second VSM pass.
  28444. *
  28445. * @type {?NodeMaterial}
  28446. * @default null
  28447. */
  28448. this.vsmMaterialHorizontal = null;
  28449. /**
  28450. * A reference to the output node which defines the
  28451. * final result of this shadow node.
  28452. *
  28453. * @type {?Node}
  28454. * @private
  28455. * @default null
  28456. */
  28457. this._node = null;
  28458. this._cameraFrameId = new WeakMap();
  28459. /**
  28460. * This flag can be used for type testing.
  28461. *
  28462. * @type {boolean}
  28463. * @readonly
  28464. * @default true
  28465. */
  28466. this.isShadowNode = true;
  28467. /**
  28468. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  28469. *
  28470. * @type {number}
  28471. * @readonly
  28472. * @default true
  28473. */
  28474. this.depthLayer = 0;
  28475. }
  28476. /**
  28477. * Setups the shadow filtering.
  28478. *
  28479. * @param {NodeBuilder} builder - A reference to the current node builder.
  28480. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  28481. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  28482. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28483. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  28484. * @param {LightShadow} inputs.shadow - The light shadow.
  28485. * @return {Node<float>} The result node of the shadow filtering.
  28486. */
  28487. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  28488. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  28489. .and( shadowCoord.x.lessThanEqual( 1 ) )
  28490. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  28491. .and( shadowCoord.y.lessThanEqual( 1 ) )
  28492. .and( shadowCoord.z.lessThanEqual( 1 ) );
  28493. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  28494. return frustumTest.select( shadowNode, float( 1 ) );
  28495. }
  28496. /**
  28497. * Setups the shadow coordinates.
  28498. *
  28499. * @param {NodeBuilder} builder - A reference to the current node builder.
  28500. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  28501. * @return {Node<vec3>} The shadow coordinates.
  28502. */
  28503. setupShadowCoord( builder, shadowPosition ) {
  28504. const { shadow } = this;
  28505. const { renderer } = builder;
  28506. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  28507. let shadowCoord = shadowPosition;
  28508. let coordZ;
  28509. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  28510. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  28511. coordZ = shadowCoord.z;
  28512. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  28513. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  28514. }
  28515. } else {
  28516. const w = shadowCoord.w;
  28517. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  28518. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  28519. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  28520. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  28521. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  28522. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  28523. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  28524. }
  28525. shadowCoord = vec3(
  28526. shadowCoord.x,
  28527. shadowCoord.y.oneMinus(), // follow webgpu standards
  28528. coordZ.add( bias )
  28529. );
  28530. return shadowCoord;
  28531. }
  28532. /**
  28533. * Returns the shadow filtering function for the given shadow type.
  28534. *
  28535. * @param {number} type - The shadow type.
  28536. * @return {Function} The filtering function.
  28537. */
  28538. getShadowFilterFn( type ) {
  28539. return _shadowFilterLib[ type ];
  28540. }
  28541. setupRenderTarget( shadow, builder ) {
  28542. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  28543. depthTexture.name = 'ShadowDepthTexture';
  28544. depthTexture.compareFunction = LessCompare;
  28545. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  28546. shadowMap.texture.name = 'ShadowMap';
  28547. shadowMap.texture.type = shadow.mapType;
  28548. shadowMap.depthTexture = depthTexture;
  28549. return { shadowMap, depthTexture };
  28550. }
  28551. /**
  28552. * Setups the shadow output node.
  28553. *
  28554. * @param {NodeBuilder} builder - A reference to the current node builder.
  28555. * @return {Node<vec3>} The shadow output node.
  28556. */
  28557. setupShadow( builder ) {
  28558. const { renderer } = builder;
  28559. const { light, shadow } = this;
  28560. const shadowMapType = renderer.shadowMap.type;
  28561. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  28562. shadow.camera.updateProjectionMatrix();
  28563. // VSM
  28564. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  28565. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  28566. if ( shadowMap.depth > 1 ) {
  28567. if ( ! shadowMap._vsmShadowMapVertical ) {
  28568. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  28569. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  28570. }
  28571. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  28572. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  28573. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  28574. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  28575. }
  28576. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  28577. } else {
  28578. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  28579. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  28580. }
  28581. let shadowPassVertical = texture( depthTexture );
  28582. if ( depthTexture.isArrayTexture ) {
  28583. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  28584. }
  28585. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  28586. if ( depthTexture.isArrayTexture ) {
  28587. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  28588. }
  28589. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  28590. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28591. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28592. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  28593. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  28594. material.name = 'VSMVertical';
  28595. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  28596. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  28597. material.name = 'VSMHorizontal';
  28598. }
  28599. //
  28600. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  28601. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  28602. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  28603. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  28604. //
  28605. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  28606. if ( filterFn === null ) {
  28607. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  28608. }
  28609. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  28610. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  28611. let shadowColor = texture( shadowMap.texture, shadowCoord );
  28612. if ( depthTexture.isArrayTexture ) {
  28613. shadowColor = shadowColor.depth( this.depthLayer );
  28614. }
  28615. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  28616. this.shadowMap = shadowMap;
  28617. this.shadow.map = shadowMap;
  28618. return shadowOutput;
  28619. }
  28620. /**
  28621. * The implementation performs the setup of the output node. An output is only
  28622. * produces if shadow mapping is globally enabled in the renderer.
  28623. *
  28624. * @param {NodeBuilder} builder - A reference to the current node builder.
  28625. * @return {ShaderCallNodeInternal} The output node.
  28626. */
  28627. setup( builder ) {
  28628. if ( builder.renderer.shadowMap.enabled === false ) return;
  28629. return Fn( () => {
  28630. let node = this._node;
  28631. this.setupShadowPosition( builder );
  28632. if ( node === null ) {
  28633. this._node = node = this.setupShadow( builder );
  28634. }
  28635. if ( builder.material.shadowNode ) { // @deprecated, r171
  28636. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  28637. }
  28638. if ( builder.material.receivedShadowNode ) {
  28639. node = builder.material.receivedShadowNode( node );
  28640. }
  28641. return node;
  28642. } )();
  28643. }
  28644. /**
  28645. * Renders the shadow. The logic of this function could be included
  28646. * into {@link ShadowNode#updateShadow} however more specialized shadow
  28647. * nodes might require a custom shadow map rendering. By having a
  28648. * dedicated method, it's easier to overwrite the default behavior.
  28649. *
  28650. * @param {NodeFrame} frame - A reference to the current node frame.
  28651. */
  28652. renderShadow( frame ) {
  28653. const { shadow, shadowMap, light } = this;
  28654. const { renderer, scene } = frame;
  28655. shadow.updateMatrices( light );
  28656. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  28657. renderer.render( scene, shadow.camera );
  28658. }
  28659. /**
  28660. * Updates the shadow.
  28661. *
  28662. * @param {NodeFrame} frame - A reference to the current node frame.
  28663. */
  28664. updateShadow( frame ) {
  28665. const { shadowMap, light, shadow } = this;
  28666. const { renderer, scene, camera } = frame;
  28667. const shadowType = renderer.shadowMap.type;
  28668. const depthVersion = shadowMap.depthTexture.version;
  28669. this._depthVersionCached = depthVersion;
  28670. const _shadowCameraLayer = shadow.camera.layers.mask;
  28671. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  28672. shadow.camera.layers.mask = camera.layers.mask;
  28673. }
  28674. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  28675. const currentMRT = renderer.getMRT();
  28676. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  28677. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  28678. scene.overrideMaterial = getShadowMaterial( light );
  28679. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  28680. renderer.setClearColor( 0x000000, 0 );
  28681. renderer.setRenderTarget( shadowMap );
  28682. this.renderShadow( frame );
  28683. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  28684. // vsm blur pass
  28685. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  28686. this.vsmPass( renderer );
  28687. }
  28688. shadow.camera.layers.mask = _shadowCameraLayer;
  28689. restoreRendererAndSceneState( renderer, scene, _rendererState );
  28690. }
  28691. /**
  28692. * For VSM additional render passes are required.
  28693. *
  28694. * @param {Renderer} renderer - A reference to the current renderer.
  28695. */
  28696. vsmPass( renderer ) {
  28697. const { shadow } = this;
  28698. const depth = this.shadowMap.depth;
  28699. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28700. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28701. renderer.setRenderTarget( this.vsmShadowMapVertical );
  28702. _quadMesh.material = this.vsmMaterialVertical;
  28703. _quadMesh.render( renderer );
  28704. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  28705. _quadMesh.material = this.vsmMaterialHorizontal;
  28706. _quadMesh.render( renderer );
  28707. }
  28708. /**
  28709. * Frees the internal resources of this shadow node.
  28710. */
  28711. dispose() {
  28712. this.shadowMap.dispose();
  28713. this.shadowMap = null;
  28714. if ( this.vsmShadowMapVertical !== null ) {
  28715. this.vsmShadowMapVertical.dispose();
  28716. this.vsmShadowMapVertical = null;
  28717. this.vsmMaterialVertical.dispose();
  28718. this.vsmMaterialVertical = null;
  28719. }
  28720. if ( this.vsmShadowMapHorizontal !== null ) {
  28721. this.vsmShadowMapHorizontal.dispose();
  28722. this.vsmShadowMapHorizontal = null;
  28723. this.vsmMaterialHorizontal.dispose();
  28724. this.vsmMaterialHorizontal = null;
  28725. }
  28726. super.dispose();
  28727. }
  28728. /**
  28729. * The implementation performs the update of the shadow map if necessary.
  28730. *
  28731. * @param {NodeFrame} frame - A reference to the current node frame.
  28732. */
  28733. updateBefore( frame ) {
  28734. const { shadow } = this;
  28735. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  28736. if ( needsUpdate ) {
  28737. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  28738. needsUpdate = false;
  28739. }
  28740. this._cameraFrameId[ frame.camera ] = frame.frameId;
  28741. }
  28742. if ( needsUpdate ) {
  28743. this.updateShadow( frame );
  28744. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  28745. shadow.needsUpdate = false;
  28746. }
  28747. }
  28748. }
  28749. }
  28750. /**
  28751. * TSL function for creating an instance of `ShadowNode`.
  28752. *
  28753. * @tsl
  28754. * @function
  28755. * @param {Light} light - The shadow casting light.
  28756. * @param {?LightShadow} [shadow] - The light shadow.
  28757. * @return {ShadowNode} The created shadow node.
  28758. */
  28759. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  28760. const _clearColor$1 = /*@__PURE__*/ new Color();
  28761. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  28762. // vector suitable for 2D texture mapping. This code uses the following layout for the
  28763. // 2D texture:
  28764. //
  28765. // xzXZ
  28766. // y Y
  28767. //
  28768. // Y - Positive y direction
  28769. // y - Negative y direction
  28770. // X - Positive x direction
  28771. // x - Negative x direction
  28772. // Z - Positive z direction
  28773. // z - Negative z direction
  28774. //
  28775. // Source and test bed:
  28776. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  28777. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  28778. const v = pos.toVar();
  28779. // Number of texels to avoid at the edge of each square
  28780. const absV = abs( v );
  28781. // Intersect unit cube
  28782. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  28783. absV.mulAssign( scaleToCube );
  28784. // Apply scale to avoid seams
  28785. // two texels less per square (one texel will do for NEAREST)
  28786. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  28787. // Unwrap
  28788. // space: -1 ... 1 range for each square
  28789. //
  28790. // #X## dim := ( 4 , 2 )
  28791. // # # center := ( 1 , 1 )
  28792. const planar = vec2( v.xy ).toVar();
  28793. const almostATexel = texelSizeY.mul( 1.5 );
  28794. const almostOne = almostATexel.oneMinus();
  28795. If( absV.z.greaterThanEqual( almostOne ), () => {
  28796. If( v.z.greaterThan( 0.0 ), () => {
  28797. planar.x.assign( sub( 4.0, v.x ) );
  28798. } );
  28799. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  28800. const signX = sign( v.x );
  28801. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  28802. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  28803. const signY = sign( v.y );
  28804. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  28805. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  28806. } );
  28807. // Transform to UV space
  28808. // scale := 0.5 / dim
  28809. // translate := ( center + 0.5 ) / dim
  28810. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  28811. } ).setLayout( {
  28812. name: 'cubeToUV',
  28813. type: 'vec2',
  28814. inputs: [
  28815. { name: 'pos', type: 'vec3' },
  28816. { name: 'texelSizeY', type: 'float' }
  28817. ]
  28818. } );
  28819. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  28820. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  28821. } );
  28822. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  28823. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28824. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  28825. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  28826. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  28827. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  28828. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  28829. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  28830. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  28831. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  28832. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  28833. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  28834. .mul( 1.0 / 9.0 );
  28835. } );
  28836. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  28837. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  28838. // the vector from the light to the world-space position of the fragment.
  28839. const lightToPosition = shadowCoord.xyz.toVar();
  28840. const lightToPositionLength = lightToPosition.length();
  28841. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  28842. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  28843. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  28844. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  28845. const result = float( 1.0 ).toVar();
  28846. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  28847. // dp = normalized distance from light to fragment position
  28848. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  28849. dp.addAssign( bias );
  28850. // bd3D = base direction 3D
  28851. const bd3D = lightToPosition.normalize();
  28852. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  28853. // percentage-closer filtering
  28854. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  28855. } );
  28856. return result;
  28857. } );
  28858. const _viewport = /*@__PURE__*/ new Vector4();
  28859. const _viewportSize = /*@__PURE__*/ new Vector2();
  28860. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  28861. /**
  28862. * Represents the shadow implementation for point light nodes.
  28863. *
  28864. * @augments ShadowNode
  28865. */
  28866. class PointShadowNode extends ShadowNode {
  28867. static get type() {
  28868. return 'PointShadowNode';
  28869. }
  28870. /**
  28871. * Constructs a new point shadow node.
  28872. *
  28873. * @param {PointLight} light - The shadow casting point light.
  28874. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28875. */
  28876. constructor( light, shadow = null ) {
  28877. super( light, shadow );
  28878. }
  28879. /**
  28880. * Overwrites the default implementation to return point light shadow specific
  28881. * filtering functions.
  28882. *
  28883. * @param {number} type - The shadow type.
  28884. * @return {Function} The filtering function.
  28885. */
  28886. getShadowFilterFn( type ) {
  28887. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  28888. }
  28889. /**
  28890. * Overwrites the default implementation so the unaltered shadow position is used.
  28891. *
  28892. * @param {NodeBuilder} builder - A reference to the current node builder.
  28893. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  28894. * @return {Node<vec3>} The shadow coordinates.
  28895. */
  28896. setupShadowCoord( builder, shadowPosition ) {
  28897. return shadowPosition;
  28898. }
  28899. /**
  28900. * Overwrites the default implementation to only use point light specific
  28901. * shadow filter functions.
  28902. *
  28903. * @param {NodeBuilder} builder - A reference to the current node builder.
  28904. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  28905. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  28906. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  28907. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28908. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  28909. * @param {LightShadow} inputs.shadow - The light shadow.
  28910. * @return {Node<float>} The result node of the shadow filtering.
  28911. */
  28912. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  28913. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  28914. }
  28915. /**
  28916. * Overwrites the default implementation with point light specific
  28917. * rendering code.
  28918. *
  28919. * @param {NodeFrame} frame - A reference to the current node frame.
  28920. */
  28921. renderShadow( frame ) {
  28922. const { shadow, shadowMap, light } = this;
  28923. const { renderer, scene } = frame;
  28924. const shadowFrameExtents = shadow.getFrameExtents();
  28925. _shadowMapSize.copy( shadow.mapSize );
  28926. _shadowMapSize.multiply( shadowFrameExtents );
  28927. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  28928. _viewportSize.copy( shadow.mapSize );
  28929. //
  28930. const previousAutoClear = renderer.autoClear;
  28931. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  28932. const previousClearAlpha = renderer.getClearAlpha();
  28933. renderer.autoClear = false;
  28934. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  28935. renderer.clear();
  28936. const viewportCount = shadow.getViewportCount();
  28937. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  28938. const viewport = shadow.getViewport( vp );
  28939. const x = _viewportSize.x * viewport.x;
  28940. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  28941. _viewport.set(
  28942. x,
  28943. y,
  28944. _viewportSize.x * viewport.z,
  28945. _viewportSize.y * viewport.w
  28946. );
  28947. shadowMap.viewport.copy( _viewport );
  28948. shadow.updateMatrices( light, vp );
  28949. renderer.render( scene, shadow.camera );
  28950. }
  28951. //
  28952. renderer.autoClear = previousAutoClear;
  28953. renderer.setClearColor( previousClearColor, previousClearAlpha );
  28954. }
  28955. }
  28956. /**
  28957. * TSL function for creating an instance of `PointShadowNode`.
  28958. *
  28959. * @tsl
  28960. * @function
  28961. * @param {PointLight} light - The shadow casting point light.
  28962. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28963. * @return {PointShadowNode} The created point shadow node.
  28964. */
  28965. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  28966. /**
  28967. * Base class for analytic light nodes.
  28968. *
  28969. * @augments LightingNode
  28970. */
  28971. class AnalyticLightNode extends LightingNode {
  28972. static get type() {
  28973. return 'AnalyticLightNode';
  28974. }
  28975. /**
  28976. * Constructs a new analytic light node.
  28977. *
  28978. * @param {?Light} [light=null] - The light source.
  28979. */
  28980. constructor( light = null ) {
  28981. super();
  28982. /**
  28983. * The light source.
  28984. *
  28985. * @type {?Light}
  28986. * @default null
  28987. */
  28988. this.light = light;
  28989. /**
  28990. * The light's color value.
  28991. *
  28992. * @type {Color}
  28993. */
  28994. this.color = new Color();
  28995. /**
  28996. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  28997. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  28998. *
  28999. * @type {Node}
  29000. */
  29001. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  29002. /**
  29003. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  29004. * The final color node is represented by a different node when using shadows.
  29005. *
  29006. * @type {?Node}
  29007. * @default null
  29008. */
  29009. this.baseColorNode = null;
  29010. /**
  29011. * Represents the light's shadow.
  29012. *
  29013. * @type {?ShadowNode}
  29014. * @default null
  29015. */
  29016. this.shadowNode = null;
  29017. /**
  29018. * Represents the light's shadow color.
  29019. *
  29020. * @type {?Node}
  29021. * @default null
  29022. */
  29023. this.shadowColorNode = null;
  29024. /**
  29025. * This flag can be used for type testing.
  29026. *
  29027. * @type {boolean}
  29028. * @readonly
  29029. * @default true
  29030. */
  29031. this.isAnalyticLightNode = true;
  29032. /**
  29033. * Overwritten since analytic light nodes are updated
  29034. * once per frame.
  29035. *
  29036. * @type {string}
  29037. * @default 'frame'
  29038. */
  29039. this.updateType = NodeUpdateType.FRAME;
  29040. }
  29041. getHash() {
  29042. return this.light.uuid;
  29043. }
  29044. /**
  29045. * Returns a node representing a direction vector which points from the current
  29046. * position in view space to the light's position in view space.
  29047. *
  29048. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29049. * @return {Node<vec3>} The light vector node.
  29050. */
  29051. getLightVector( builder ) {
  29052. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  29053. }
  29054. /**
  29055. * Sets up the direct lighting for the analytic light node.
  29056. *
  29057. * @abstract
  29058. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29059. * @return {Object|undefined} The direct light data (color and direction).
  29060. */
  29061. setupDirect( /*builder*/ ) { }
  29062. /**
  29063. * Sets up the direct rect area lighting for the analytic light node.
  29064. *
  29065. * @abstract
  29066. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29067. * @return {Object|undefined} The direct rect area light data.
  29068. */
  29069. setupDirectRectArea( /*builder*/ ) { }
  29070. /**
  29071. * Setups the shadow node for this light. The method exists so concrete light classes
  29072. * can setup different types of shadow nodes.
  29073. *
  29074. * @return {ShadowNode} The created shadow node.
  29075. */
  29076. setupShadowNode() {
  29077. return shadow( this.light );
  29078. }
  29079. /**
  29080. * Setups the shadow for this light. This method is only executed if the light
  29081. * cast shadows and the current build object receives shadows. It incorporates
  29082. * shadows into the lighting computation.
  29083. *
  29084. * @param {NodeBuilder} builder - The current node builder.
  29085. */
  29086. setupShadow( builder ) {
  29087. const { renderer } = builder;
  29088. if ( renderer.shadowMap.enabled === false ) return;
  29089. let shadowColorNode = this.shadowColorNode;
  29090. if ( shadowColorNode === null ) {
  29091. const customShadowNode = this.light.shadow.shadowNode;
  29092. let shadowNode;
  29093. if ( customShadowNode !== undefined ) {
  29094. shadowNode = nodeObject( customShadowNode );
  29095. } else {
  29096. shadowNode = this.setupShadowNode();
  29097. }
  29098. this.shadowNode = shadowNode;
  29099. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  29100. this.baseColorNode = this.colorNode;
  29101. }
  29102. //
  29103. this.colorNode = shadowColorNode;
  29104. }
  29105. /**
  29106. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  29107. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  29108. * invocate the respective interface methods.
  29109. *
  29110. * @param {NodeBuilder} builder - The current node builder.
  29111. */
  29112. setup( builder ) {
  29113. this.colorNode = this.baseColorNode || this.colorNode;
  29114. if ( this.light.castShadow ) {
  29115. if ( builder.object.receiveShadow ) {
  29116. this.setupShadow( builder );
  29117. }
  29118. } else if ( this.shadowNode !== null ) {
  29119. this.shadowNode.dispose();
  29120. this.shadowNode = null;
  29121. this.shadowColorNode = null;
  29122. }
  29123. const directLightData = this.setupDirect( builder );
  29124. const directRectAreaLightData = this.setupDirectRectArea( builder );
  29125. if ( directLightData ) {
  29126. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  29127. }
  29128. if ( directRectAreaLightData ) {
  29129. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  29130. }
  29131. }
  29132. /**
  29133. * The update method is used to update light uniforms per frame.
  29134. * Potentially overwritten in concrete light nodes to update light
  29135. * specific uniforms.
  29136. *
  29137. * @param {NodeFrame} frame - A reference to the current node frame.
  29138. */
  29139. update( /*frame*/ ) {
  29140. const { light } = this;
  29141. this.color.copy( light.color ).multiplyScalar( light.intensity );
  29142. }
  29143. }
  29144. /**
  29145. * Represents a `discard` shader operation in TSL.
  29146. *
  29147. * @method
  29148. * @param {Object} inputs - The input parameter object.
  29149. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  29150. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  29151. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  29152. * @return {Node<float>} The distance falloff.
  29153. */
  29154. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  29155. // based upon Frostbite 3 Moving to Physically-based Rendering
  29156. // page 32, equation 26: E[window1]
  29157. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29158. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  29159. return cutoffDistance.greaterThan( 0 ).select(
  29160. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  29161. distanceFalloff
  29162. );
  29163. } ); // validated
  29164. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  29165. const lightDirection = lightVector.normalize();
  29166. const lightDistance = lightVector.length();
  29167. const attenuation = getDistanceAttenuation( {
  29168. lightDistance,
  29169. cutoffDistance,
  29170. decayExponent
  29171. } );
  29172. const lightColor = color.mul( attenuation );
  29173. return { lightDirection, lightColor };
  29174. };
  29175. /**
  29176. * Module for representing point lights as nodes.
  29177. *
  29178. * @augments AnalyticLightNode
  29179. */
  29180. class PointLightNode extends AnalyticLightNode {
  29181. static get type() {
  29182. return 'PointLightNode';
  29183. }
  29184. /**
  29185. * Constructs a new point light node.
  29186. *
  29187. * @param {?PointLight} [light=null] - The point light source.
  29188. */
  29189. constructor( light = null ) {
  29190. super( light );
  29191. /**
  29192. * Uniform node representing the cutoff distance.
  29193. *
  29194. * @type {UniformNode<float>}
  29195. */
  29196. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  29197. /**
  29198. * Uniform node representing the decay exponent.
  29199. *
  29200. * @type {UniformNode<float>}
  29201. */
  29202. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  29203. }
  29204. /**
  29205. * Overwritten to updated point light specific uniforms.
  29206. *
  29207. * @param {NodeFrame} frame - A reference to the current node frame.
  29208. */
  29209. update( frame ) {
  29210. const { light } = this;
  29211. super.update( frame );
  29212. this.cutoffDistanceNode.value = light.distance;
  29213. this.decayExponentNode.value = light.decay;
  29214. }
  29215. /**
  29216. * Overwritten to setup point light specific shadow.
  29217. *
  29218. * @return {PointShadowNode}
  29219. */
  29220. setupShadowNode() {
  29221. return pointShadow( this.light );
  29222. }
  29223. setupDirect( builder ) {
  29224. return directPointLight( {
  29225. color: this.colorNode,
  29226. lightVector: this.getLightVector( builder ),
  29227. cutoffDistance: this.cutoffDistanceNode,
  29228. decayExponent: this.decayExponentNode
  29229. } );
  29230. }
  29231. }
  29232. /**
  29233. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  29234. *
  29235. * @tsl
  29236. * @function
  29237. * @param {Node<vec2>} coord - The uv coordinates.
  29238. * @return {Node<float>} The result data.
  29239. */
  29240. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  29241. const uv = coord.mul( 2.0 );
  29242. const cx = uv.x.floor();
  29243. const cy = uv.y.floor();
  29244. const result = cx.add( cy ).mod( 2.0 );
  29245. return result.sign();
  29246. } );
  29247. /**
  29248. * Generates a circle based on the uv coordinates.
  29249. *
  29250. * @tsl
  29251. * @function
  29252. * @param {Node<vec2>} coord - The uv to generate the circle.
  29253. * @return {Node<float>} The circle shape.
  29254. */
  29255. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  29256. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  29257. let alpha;
  29258. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  29259. const dlen = float( len2.fwidth() ).toVar();
  29260. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  29261. } else {
  29262. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  29263. }
  29264. return alpha;
  29265. } );
  29266. // Three.js Transpiler
  29267. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  29268. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  29269. const f = float( f_immutable ).toVar();
  29270. const t = float( t_immutable ).toVar();
  29271. const b = bool( b_immutable ).toVar();
  29272. return select( b, t, f );
  29273. } ).setLayout( {
  29274. name: 'mx_select',
  29275. type: 'float',
  29276. inputs: [
  29277. { name: 'b', type: 'bool' },
  29278. { name: 't', type: 'float' },
  29279. { name: 'f', type: 'float' }
  29280. ]
  29281. } );
  29282. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  29283. const b = bool( b_immutable ).toVar();
  29284. const val = float( val_immutable ).toVar();
  29285. return select( b, val.negate(), val );
  29286. } ).setLayout( {
  29287. name: 'mx_negate_if',
  29288. type: 'float',
  29289. inputs: [
  29290. { name: 'val', type: 'float' },
  29291. { name: 'b', type: 'bool' }
  29292. ]
  29293. } );
  29294. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29295. const x = float( x_immutable ).toVar();
  29296. return int( floor( x ) );
  29297. } ).setLayout( {
  29298. name: 'mx_floor',
  29299. type: 'int',
  29300. inputs: [
  29301. { name: 'x', type: 'float' }
  29302. ]
  29303. } );
  29304. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  29305. const x = float( x_immutable ).toVar();
  29306. i.assign( mx_floor( x ) );
  29307. return x.sub( float( i ) );
  29308. } );
  29309. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  29310. const t = float( t_immutable ).toVar();
  29311. const s = float( s_immutable ).toVar();
  29312. const v3 = float( v3_immutable ).toVar();
  29313. const v2 = float( v2_immutable ).toVar();
  29314. const v1 = float( v1_immutable ).toVar();
  29315. const v0 = float( v0_immutable ).toVar();
  29316. const s1 = float( sub( 1.0, s ) ).toVar();
  29317. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  29318. } ).setLayout( {
  29319. name: 'mx_bilerp_0',
  29320. type: 'float',
  29321. inputs: [
  29322. { name: 'v0', type: 'float' },
  29323. { name: 'v1', type: 'float' },
  29324. { name: 'v2', type: 'float' },
  29325. { name: 'v3', type: 'float' },
  29326. { name: 's', type: 'float' },
  29327. { name: 't', type: 'float' }
  29328. ]
  29329. } );
  29330. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  29331. const t = float( t_immutable ).toVar();
  29332. const s = float( s_immutable ).toVar();
  29333. const v3 = vec3( v3_immutable ).toVar();
  29334. const v2 = vec3( v2_immutable ).toVar();
  29335. const v1 = vec3( v1_immutable ).toVar();
  29336. const v0 = vec3( v0_immutable ).toVar();
  29337. const s1 = float( sub( 1.0, s ) ).toVar();
  29338. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  29339. } ).setLayout( {
  29340. name: 'mx_bilerp_1',
  29341. type: 'vec3',
  29342. inputs: [
  29343. { name: 'v0', type: 'vec3' },
  29344. { name: 'v1', type: 'vec3' },
  29345. { name: 'v2', type: 'vec3' },
  29346. { name: 'v3', type: 'vec3' },
  29347. { name: 's', type: 'float' },
  29348. { name: 't', type: 'float' }
  29349. ]
  29350. } );
  29351. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  29352. 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 ] ) => {
  29353. const r = float( r_immutable ).toVar();
  29354. const t = float( t_immutable ).toVar();
  29355. const s = float( s_immutable ).toVar();
  29356. const v7 = float( v7_immutable ).toVar();
  29357. const v6 = float( v6_immutable ).toVar();
  29358. const v5 = float( v5_immutable ).toVar();
  29359. const v4 = float( v4_immutable ).toVar();
  29360. const v3 = float( v3_immutable ).toVar();
  29361. const v2 = float( v2_immutable ).toVar();
  29362. const v1 = float( v1_immutable ).toVar();
  29363. const v0 = float( v0_immutable ).toVar();
  29364. const s1 = float( sub( 1.0, s ) ).toVar();
  29365. const t1 = float( sub( 1.0, t ) ).toVar();
  29366. const r1 = float( sub( 1.0, r ) ).toVar();
  29367. 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 ) ) ) ) ) );
  29368. } ).setLayout( {
  29369. name: 'mx_trilerp_0',
  29370. type: 'float',
  29371. inputs: [
  29372. { name: 'v0', type: 'float' },
  29373. { name: 'v1', type: 'float' },
  29374. { name: 'v2', type: 'float' },
  29375. { name: 'v3', type: 'float' },
  29376. { name: 'v4', type: 'float' },
  29377. { name: 'v5', type: 'float' },
  29378. { name: 'v6', type: 'float' },
  29379. { name: 'v7', type: 'float' },
  29380. { name: 's', type: 'float' },
  29381. { name: 't', type: 'float' },
  29382. { name: 'r', type: 'float' }
  29383. ]
  29384. } );
  29385. 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 ] ) => {
  29386. const r = float( r_immutable ).toVar();
  29387. const t = float( t_immutable ).toVar();
  29388. const s = float( s_immutable ).toVar();
  29389. const v7 = vec3( v7_immutable ).toVar();
  29390. const v6 = vec3( v6_immutable ).toVar();
  29391. const v5 = vec3( v5_immutable ).toVar();
  29392. const v4 = vec3( v4_immutable ).toVar();
  29393. const v3 = vec3( v3_immutable ).toVar();
  29394. const v2 = vec3( v2_immutable ).toVar();
  29395. const v1 = vec3( v1_immutable ).toVar();
  29396. const v0 = vec3( v0_immutable ).toVar();
  29397. const s1 = float( sub( 1.0, s ) ).toVar();
  29398. const t1 = float( sub( 1.0, t ) ).toVar();
  29399. const r1 = float( sub( 1.0, r ) ).toVar();
  29400. 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 ) ) ) ) ) );
  29401. } ).setLayout( {
  29402. name: 'mx_trilerp_1',
  29403. type: 'vec3',
  29404. inputs: [
  29405. { name: 'v0', type: 'vec3' },
  29406. { name: 'v1', type: 'vec3' },
  29407. { name: 'v2', type: 'vec3' },
  29408. { name: 'v3', type: 'vec3' },
  29409. { name: 'v4', type: 'vec3' },
  29410. { name: 'v5', type: 'vec3' },
  29411. { name: 'v6', type: 'vec3' },
  29412. { name: 'v7', type: 'vec3' },
  29413. { name: 's', type: 'float' },
  29414. { name: 't', type: 'float' },
  29415. { name: 'r', type: 'float' }
  29416. ]
  29417. } );
  29418. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  29419. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  29420. const y = float( y_immutable ).toVar();
  29421. const x = float( x_immutable ).toVar();
  29422. const hash = uint( hash_immutable ).toVar();
  29423. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  29424. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  29425. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  29426. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  29427. } ).setLayout( {
  29428. name: 'mx_gradient_float_0',
  29429. type: 'float',
  29430. inputs: [
  29431. { name: 'hash', type: 'uint' },
  29432. { name: 'x', type: 'float' },
  29433. { name: 'y', type: 'float' }
  29434. ]
  29435. } );
  29436. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  29437. const z = float( z_immutable ).toVar();
  29438. const y = float( y_immutable ).toVar();
  29439. const x = float( x_immutable ).toVar();
  29440. const hash = uint( hash_immutable ).toVar();
  29441. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  29442. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  29443. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  29444. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  29445. } ).setLayout( {
  29446. name: 'mx_gradient_float_1',
  29447. type: 'float',
  29448. inputs: [
  29449. { name: 'hash', type: 'uint' },
  29450. { name: 'x', type: 'float' },
  29451. { name: 'y', type: 'float' },
  29452. { name: 'z', type: 'float' }
  29453. ]
  29454. } );
  29455. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  29456. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  29457. const y = float( y_immutable ).toVar();
  29458. const x = float( x_immutable ).toVar();
  29459. const hash = uvec3( hash_immutable ).toVar();
  29460. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  29461. } ).setLayout( {
  29462. name: 'mx_gradient_vec3_0',
  29463. type: 'vec3',
  29464. inputs: [
  29465. { name: 'hash', type: 'uvec3' },
  29466. { name: 'x', type: 'float' },
  29467. { name: 'y', type: 'float' }
  29468. ]
  29469. } );
  29470. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  29471. const z = float( z_immutable ).toVar();
  29472. const y = float( y_immutable ).toVar();
  29473. const x = float( x_immutable ).toVar();
  29474. const hash = uvec3( hash_immutable ).toVar();
  29475. 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 ) );
  29476. } ).setLayout( {
  29477. name: 'mx_gradient_vec3_1',
  29478. type: 'vec3',
  29479. inputs: [
  29480. { name: 'hash', type: 'uvec3' },
  29481. { name: 'x', type: 'float' },
  29482. { name: 'y', type: 'float' },
  29483. { name: 'z', type: 'float' }
  29484. ]
  29485. } );
  29486. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  29487. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29488. const v = float( v_immutable ).toVar();
  29489. return mul( 0.6616, v );
  29490. } ).setLayout( {
  29491. name: 'mx_gradient_scale2d_0',
  29492. type: 'float',
  29493. inputs: [
  29494. { name: 'v', type: 'float' }
  29495. ]
  29496. } );
  29497. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29498. const v = float( v_immutable ).toVar();
  29499. return mul( 0.9820, v );
  29500. } ).setLayout( {
  29501. name: 'mx_gradient_scale3d_0',
  29502. type: 'float',
  29503. inputs: [
  29504. { name: 'v', type: 'float' }
  29505. ]
  29506. } );
  29507. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29508. const v = vec3( v_immutable ).toVar();
  29509. return mul( 0.6616, v );
  29510. } ).setLayout( {
  29511. name: 'mx_gradient_scale2d_1',
  29512. type: 'vec3',
  29513. inputs: [
  29514. { name: 'v', type: 'vec3' }
  29515. ]
  29516. } );
  29517. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  29518. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29519. const v = vec3( v_immutable ).toVar();
  29520. return mul( 0.9820, v );
  29521. } ).setLayout( {
  29522. name: 'mx_gradient_scale3d_1',
  29523. type: 'vec3',
  29524. inputs: [
  29525. { name: 'v', type: 'vec3' }
  29526. ]
  29527. } );
  29528. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  29529. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  29530. const k = int( k_immutable ).toVar();
  29531. const x = uint( x_immutable ).toVar();
  29532. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  29533. } ).setLayout( {
  29534. name: 'mx_rotl32',
  29535. type: 'uint',
  29536. inputs: [
  29537. { name: 'x', type: 'uint' },
  29538. { name: 'k', type: 'int' }
  29539. ]
  29540. } );
  29541. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  29542. a.subAssign( c );
  29543. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  29544. c.addAssign( b );
  29545. b.subAssign( a );
  29546. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  29547. a.addAssign( c );
  29548. c.subAssign( b );
  29549. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  29550. b.addAssign( a );
  29551. a.subAssign( c );
  29552. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  29553. c.addAssign( b );
  29554. b.subAssign( a );
  29555. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  29556. a.addAssign( c );
  29557. c.subAssign( b );
  29558. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  29559. b.addAssign( a );
  29560. } );
  29561. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  29562. const c = uint( c_immutable ).toVar();
  29563. const b = uint( b_immutable ).toVar();
  29564. const a = uint( a_immutable ).toVar();
  29565. c.bitXorAssign( b );
  29566. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  29567. a.bitXorAssign( c );
  29568. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  29569. b.bitXorAssign( a );
  29570. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  29571. c.bitXorAssign( b );
  29572. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  29573. a.bitXorAssign( c );
  29574. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  29575. b.bitXorAssign( a );
  29576. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  29577. c.bitXorAssign( b );
  29578. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  29579. return c;
  29580. } ).setLayout( {
  29581. name: 'mx_bjfinal',
  29582. type: 'uint',
  29583. inputs: [
  29584. { name: 'a', type: 'uint' },
  29585. { name: 'b', type: 'uint' },
  29586. { name: 'c', type: 'uint' }
  29587. ]
  29588. } );
  29589. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  29590. const bits = uint( bits_immutable ).toVar();
  29591. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  29592. } ).setLayout( {
  29593. name: 'mx_bits_to_01',
  29594. type: 'float',
  29595. inputs: [
  29596. { name: 'bits', type: 'uint' }
  29597. ]
  29598. } );
  29599. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  29600. const t = float( t_immutable ).toVar();
  29601. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  29602. } ).setLayout( {
  29603. name: 'mx_fade',
  29604. type: 'float',
  29605. inputs: [
  29606. { name: 't', type: 'float' }
  29607. ]
  29608. } );
  29609. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29610. const x = int( x_immutable ).toVar();
  29611. const len = uint( uint( 1 ) ).toVar();
  29612. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  29613. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  29614. } ).setLayout( {
  29615. name: 'mx_hash_int_0',
  29616. type: 'uint',
  29617. inputs: [
  29618. { name: 'x', type: 'int' }
  29619. ]
  29620. } );
  29621. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  29622. const y = int( y_immutable ).toVar();
  29623. const x = int( x_immutable ).toVar();
  29624. const len = uint( uint( 2 ) ).toVar();
  29625. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29626. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29627. a.addAssign( uint( x ) );
  29628. b.addAssign( uint( y ) );
  29629. return mx_bjfinal( a, b, c );
  29630. } ).setLayout( {
  29631. name: 'mx_hash_int_1',
  29632. type: 'uint',
  29633. inputs: [
  29634. { name: 'x', type: 'int' },
  29635. { name: 'y', type: 'int' }
  29636. ]
  29637. } );
  29638. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  29639. const z = int( z_immutable ).toVar();
  29640. const y = int( y_immutable ).toVar();
  29641. const x = int( x_immutable ).toVar();
  29642. const len = uint( uint( 3 ) ).toVar();
  29643. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29644. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29645. a.addAssign( uint( x ) );
  29646. b.addAssign( uint( y ) );
  29647. c.addAssign( uint( z ) );
  29648. return mx_bjfinal( a, b, c );
  29649. } ).setLayout( {
  29650. name: 'mx_hash_int_2',
  29651. type: 'uint',
  29652. inputs: [
  29653. { name: 'x', type: 'int' },
  29654. { name: 'y', type: 'int' },
  29655. { name: 'z', type: 'int' }
  29656. ]
  29657. } );
  29658. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  29659. const xx = int( xx_immutable ).toVar();
  29660. const z = int( z_immutable ).toVar();
  29661. const y = int( y_immutable ).toVar();
  29662. const x = int( x_immutable ).toVar();
  29663. const len = uint( uint( 4 ) ).toVar();
  29664. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29665. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29666. a.addAssign( uint( x ) );
  29667. b.addAssign( uint( y ) );
  29668. c.addAssign( uint( z ) );
  29669. mx_bjmix( a, b, c );
  29670. a.addAssign( uint( xx ) );
  29671. return mx_bjfinal( a, b, c );
  29672. } ).setLayout( {
  29673. name: 'mx_hash_int_3',
  29674. type: 'uint',
  29675. inputs: [
  29676. { name: 'x', type: 'int' },
  29677. { name: 'y', type: 'int' },
  29678. { name: 'z', type: 'int' },
  29679. { name: 'xx', type: 'int' }
  29680. ]
  29681. } );
  29682. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  29683. const yy = int( yy_immutable ).toVar();
  29684. const xx = int( xx_immutable ).toVar();
  29685. const z = int( z_immutable ).toVar();
  29686. const y = int( y_immutable ).toVar();
  29687. const x = int( x_immutable ).toVar();
  29688. const len = uint( uint( 5 ) ).toVar();
  29689. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29690. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29691. a.addAssign( uint( x ) );
  29692. b.addAssign( uint( y ) );
  29693. c.addAssign( uint( z ) );
  29694. mx_bjmix( a, b, c );
  29695. a.addAssign( uint( xx ) );
  29696. b.addAssign( uint( yy ) );
  29697. return mx_bjfinal( a, b, c );
  29698. } ).setLayout( {
  29699. name: 'mx_hash_int_4',
  29700. type: 'uint',
  29701. inputs: [
  29702. { name: 'x', type: 'int' },
  29703. { name: 'y', type: 'int' },
  29704. { name: 'z', type: 'int' },
  29705. { name: 'xx', type: 'int' },
  29706. { name: 'yy', type: 'int' }
  29707. ]
  29708. } );
  29709. 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 ] );
  29710. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  29711. const y = int( y_immutable ).toVar();
  29712. const x = int( x_immutable ).toVar();
  29713. const h = uint( mx_hash_int( x, y ) ).toVar();
  29714. const result = uvec3().toVar();
  29715. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29716. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29717. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29718. return result;
  29719. } ).setLayout( {
  29720. name: 'mx_hash_vec3_0',
  29721. type: 'uvec3',
  29722. inputs: [
  29723. { name: 'x', type: 'int' },
  29724. { name: 'y', type: 'int' }
  29725. ]
  29726. } );
  29727. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  29728. const z = int( z_immutable ).toVar();
  29729. const y = int( y_immutable ).toVar();
  29730. const x = int( x_immutable ).toVar();
  29731. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  29732. const result = uvec3().toVar();
  29733. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29734. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29735. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29736. return result;
  29737. } ).setLayout( {
  29738. name: 'mx_hash_vec3_1',
  29739. type: 'uvec3',
  29740. inputs: [
  29741. { name: 'x', type: 'int' },
  29742. { name: 'y', type: 'int' },
  29743. { name: 'z', type: 'int' }
  29744. ]
  29745. } );
  29746. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  29747. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29748. const p = vec2( p_immutable ).toVar();
  29749. const X = int().toVar(), Y = int().toVar();
  29750. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29751. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29752. const u = float( mx_fade( fx ) ).toVar();
  29753. const v = float( mx_fade( fy ) ).toVar();
  29754. 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();
  29755. return mx_gradient_scale2d( result );
  29756. } ).setLayout( {
  29757. name: 'mx_perlin_noise_float_0',
  29758. type: 'float',
  29759. inputs: [
  29760. { name: 'p', type: 'vec2' }
  29761. ]
  29762. } );
  29763. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29764. const p = vec3( p_immutable ).toVar();
  29765. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29766. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29767. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29768. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29769. const u = float( mx_fade( fx ) ).toVar();
  29770. const v = float( mx_fade( fy ) ).toVar();
  29771. const w = float( mx_fade( fz ) ).toVar();
  29772. 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();
  29773. return mx_gradient_scale3d( result );
  29774. } ).setLayout( {
  29775. name: 'mx_perlin_noise_float_1',
  29776. type: 'float',
  29777. inputs: [
  29778. { name: 'p', type: 'vec3' }
  29779. ]
  29780. } );
  29781. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  29782. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29783. const p = vec2( p_immutable ).toVar();
  29784. const X = int().toVar(), Y = int().toVar();
  29785. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29786. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29787. const u = float( mx_fade( fx ) ).toVar();
  29788. const v = float( mx_fade( fy ) ).toVar();
  29789. 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();
  29790. return mx_gradient_scale2d( result );
  29791. } ).setLayout( {
  29792. name: 'mx_perlin_noise_vec3_0',
  29793. type: 'vec3',
  29794. inputs: [
  29795. { name: 'p', type: 'vec2' }
  29796. ]
  29797. } );
  29798. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29799. const p = vec3( p_immutable ).toVar();
  29800. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29801. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29802. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29803. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29804. const u = float( mx_fade( fx ) ).toVar();
  29805. const v = float( mx_fade( fy ) ).toVar();
  29806. const w = float( mx_fade( fz ) ).toVar();
  29807. 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();
  29808. return mx_gradient_scale3d( result );
  29809. } ).setLayout( {
  29810. name: 'mx_perlin_noise_vec3_1',
  29811. type: 'vec3',
  29812. inputs: [
  29813. { name: 'p', type: 'vec3' }
  29814. ]
  29815. } );
  29816. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  29817. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29818. const p = float( p_immutable ).toVar();
  29819. const ix = int( mx_floor( p ) ).toVar();
  29820. return mx_bits_to_01( mx_hash_int( ix ) );
  29821. } ).setLayout( {
  29822. name: 'mx_cell_noise_float_0',
  29823. type: 'float',
  29824. inputs: [
  29825. { name: 'p', type: 'float' }
  29826. ]
  29827. } );
  29828. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29829. const p = vec2( p_immutable ).toVar();
  29830. const ix = int( mx_floor( p.x ) ).toVar();
  29831. const iy = int( mx_floor( p.y ) ).toVar();
  29832. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  29833. } ).setLayout( {
  29834. name: 'mx_cell_noise_float_1',
  29835. type: 'float',
  29836. inputs: [
  29837. { name: 'p', type: 'vec2' }
  29838. ]
  29839. } );
  29840. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29841. const p = vec3( p_immutable ).toVar();
  29842. const ix = int( mx_floor( p.x ) ).toVar();
  29843. const iy = int( mx_floor( p.y ) ).toVar();
  29844. const iz = int( mx_floor( p.z ) ).toVar();
  29845. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  29846. } ).setLayout( {
  29847. name: 'mx_cell_noise_float_2',
  29848. type: 'float',
  29849. inputs: [
  29850. { name: 'p', type: 'vec3' }
  29851. ]
  29852. } );
  29853. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29854. const p = vec4( p_immutable ).toVar();
  29855. const ix = int( mx_floor( p.x ) ).toVar();
  29856. const iy = int( mx_floor( p.y ) ).toVar();
  29857. const iz = int( mx_floor( p.z ) ).toVar();
  29858. const iw = int( mx_floor( p.w ) ).toVar();
  29859. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  29860. } ).setLayout( {
  29861. name: 'mx_cell_noise_float_3',
  29862. type: 'float',
  29863. inputs: [
  29864. { name: 'p', type: 'vec4' }
  29865. ]
  29866. } );
  29867. 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 ] );
  29868. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29869. const p = float( p_immutable ).toVar();
  29870. const ix = int( mx_floor( p ) ).toVar();
  29871. 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 ) ) ) );
  29872. } ).setLayout( {
  29873. name: 'mx_cell_noise_vec3_0',
  29874. type: 'vec3',
  29875. inputs: [
  29876. { name: 'p', type: 'float' }
  29877. ]
  29878. } );
  29879. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29880. const p = vec2( p_immutable ).toVar();
  29881. const ix = int( mx_floor( p.x ) ).toVar();
  29882. const iy = int( mx_floor( p.y ) ).toVar();
  29883. 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 ) ) ) );
  29884. } ).setLayout( {
  29885. name: 'mx_cell_noise_vec3_1',
  29886. type: 'vec3',
  29887. inputs: [
  29888. { name: 'p', type: 'vec2' }
  29889. ]
  29890. } );
  29891. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29892. const p = vec3( p_immutable ).toVar();
  29893. const ix = int( mx_floor( p.x ) ).toVar();
  29894. const iy = int( mx_floor( p.y ) ).toVar();
  29895. const iz = int( mx_floor( p.z ) ).toVar();
  29896. 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 ) ) ) );
  29897. } ).setLayout( {
  29898. name: 'mx_cell_noise_vec3_2',
  29899. type: 'vec3',
  29900. inputs: [
  29901. { name: 'p', type: 'vec3' }
  29902. ]
  29903. } );
  29904. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29905. const p = vec4( p_immutable ).toVar();
  29906. const ix = int( mx_floor( p.x ) ).toVar();
  29907. const iy = int( mx_floor( p.y ) ).toVar();
  29908. const iz = int( mx_floor( p.z ) ).toVar();
  29909. const iw = int( mx_floor( p.w ) ).toVar();
  29910. 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 ) ) ) );
  29911. } ).setLayout( {
  29912. name: 'mx_cell_noise_vec3_3',
  29913. type: 'vec3',
  29914. inputs: [
  29915. { name: 'p', type: 'vec4' }
  29916. ]
  29917. } );
  29918. 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 ] );
  29919. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29920. const diminish = float( diminish_immutable ).toVar();
  29921. const lacunarity = float( lacunarity_immutable ).toVar();
  29922. const octaves = int( octaves_immutable ).toVar();
  29923. const p = vec3( p_immutable ).toVar();
  29924. const result = float( 0.0 ).toVar();
  29925. const amplitude = float( 1.0 ).toVar();
  29926. Loop( octaves, () => {
  29927. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  29928. amplitude.mulAssign( diminish );
  29929. p.mulAssign( lacunarity );
  29930. } );
  29931. return result;
  29932. } ).setLayout( {
  29933. name: 'mx_fractal_noise_float',
  29934. type: 'float',
  29935. inputs: [
  29936. { name: 'p', type: 'vec3' },
  29937. { name: 'octaves', type: 'int' },
  29938. { name: 'lacunarity', type: 'float' },
  29939. { name: 'diminish', type: 'float' }
  29940. ]
  29941. } );
  29942. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29943. const diminish = float( diminish_immutable ).toVar();
  29944. const lacunarity = float( lacunarity_immutable ).toVar();
  29945. const octaves = int( octaves_immutable ).toVar();
  29946. const p = vec3( p_immutable ).toVar();
  29947. const result = vec3( 0.0 ).toVar();
  29948. const amplitude = float( 1.0 ).toVar();
  29949. Loop( octaves, () => {
  29950. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  29951. amplitude.mulAssign( diminish );
  29952. p.mulAssign( lacunarity );
  29953. } );
  29954. return result;
  29955. } ).setLayout( {
  29956. name: 'mx_fractal_noise_vec3',
  29957. type: 'vec3',
  29958. inputs: [
  29959. { name: 'p', type: 'vec3' },
  29960. { name: 'octaves', type: 'int' },
  29961. { name: 'lacunarity', type: 'float' },
  29962. { name: 'diminish', type: 'float' }
  29963. ]
  29964. } );
  29965. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29966. const diminish = float( diminish_immutable ).toVar();
  29967. const lacunarity = float( lacunarity_immutable ).toVar();
  29968. const octaves = int( octaves_immutable ).toVar();
  29969. const p = vec3( p_immutable ).toVar();
  29970. 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 ) );
  29971. } ).setLayout( {
  29972. name: 'mx_fractal_noise_vec2',
  29973. type: 'vec2',
  29974. inputs: [
  29975. { name: 'p', type: 'vec3' },
  29976. { name: 'octaves', type: 'int' },
  29977. { name: 'lacunarity', type: 'float' },
  29978. { name: 'diminish', type: 'float' }
  29979. ]
  29980. } );
  29981. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29982. const diminish = float( diminish_immutable ).toVar();
  29983. const lacunarity = float( lacunarity_immutable ).toVar();
  29984. const octaves = int( octaves_immutable ).toVar();
  29985. const p = vec3( p_immutable ).toVar();
  29986. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  29987. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  29988. return vec4( c, f );
  29989. } ).setLayout( {
  29990. name: 'mx_fractal_noise_vec4',
  29991. type: 'vec4',
  29992. inputs: [
  29993. { name: 'p', type: 'vec3' },
  29994. { name: 'octaves', type: 'int' },
  29995. { name: 'lacunarity', type: 'float' },
  29996. { name: 'diminish', type: 'float' }
  29997. ]
  29998. } );
  29999. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  30000. const metric = int( metric_immutable ).toVar();
  30001. const jitter = float( jitter_immutable ).toVar();
  30002. const yoff = int( yoff_immutable ).toVar();
  30003. const xoff = int( xoff_immutable ).toVar();
  30004. const y = int( y_immutable ).toVar();
  30005. const x = int( x_immutable ).toVar();
  30006. const p = vec2( p_immutable ).toVar();
  30007. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  30008. const off = vec2( tmp.x, tmp.y ).toVar();
  30009. off.subAssign( 0.5 );
  30010. off.mulAssign( jitter );
  30011. off.addAssign( 0.5 );
  30012. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  30013. const diff = vec2( cellpos.sub( p ) ).toVar();
  30014. If( metric.equal( int( 2 ) ), () => {
  30015. return abs( diff.x ).add( abs( diff.y ) );
  30016. } );
  30017. If( metric.equal( int( 3 ) ), () => {
  30018. return max$1( abs( diff.x ), abs( diff.y ) );
  30019. } );
  30020. return dot( diff, diff );
  30021. } ).setLayout( {
  30022. name: 'mx_worley_distance_0',
  30023. type: 'float',
  30024. inputs: [
  30025. { name: 'p', type: 'vec2' },
  30026. { name: 'x', type: 'int' },
  30027. { name: 'y', type: 'int' },
  30028. { name: 'xoff', type: 'int' },
  30029. { name: 'yoff', type: 'int' },
  30030. { name: 'jitter', type: 'float' },
  30031. { name: 'metric', type: 'int' }
  30032. ]
  30033. } );
  30034. 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 ] ) => {
  30035. const metric = int( metric_immutable ).toVar();
  30036. const jitter = float( jitter_immutable ).toVar();
  30037. const zoff = int( zoff_immutable ).toVar();
  30038. const yoff = int( yoff_immutable ).toVar();
  30039. const xoff = int( xoff_immutable ).toVar();
  30040. const z = int( z_immutable ).toVar();
  30041. const y = int( y_immutable ).toVar();
  30042. const x = int( x_immutable ).toVar();
  30043. const p = vec3( p_immutable ).toVar();
  30044. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  30045. off.subAssign( 0.5 );
  30046. off.mulAssign( jitter );
  30047. off.addAssign( 0.5 );
  30048. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  30049. const diff = vec3( cellpos.sub( p ) ).toVar();
  30050. If( metric.equal( int( 2 ) ), () => {
  30051. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  30052. } );
  30053. If( metric.equal( int( 3 ) ), () => {
  30054. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  30055. } );
  30056. return dot( diff, diff );
  30057. } ).setLayout( {
  30058. name: 'mx_worley_distance_1',
  30059. type: 'float',
  30060. inputs: [
  30061. { name: 'p', type: 'vec3' },
  30062. { name: 'x', type: 'int' },
  30063. { name: 'y', type: 'int' },
  30064. { name: 'z', type: 'int' },
  30065. { name: 'xoff', type: 'int' },
  30066. { name: 'yoff', type: 'int' },
  30067. { name: 'zoff', type: 'int' },
  30068. { name: 'jitter', type: 'float' },
  30069. { name: 'metric', type: 'int' }
  30070. ]
  30071. } );
  30072. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  30073. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30074. const metric = int( metric_immutable ).toVar();
  30075. const jitter = float( jitter_immutable ).toVar();
  30076. const p = vec2( p_immutable ).toVar();
  30077. const X = int().toVar(), Y = int().toVar();
  30078. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30079. const sqdist = float( 1e6 ).toVar();
  30080. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30081. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30082. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30083. sqdist.assign( min$1( sqdist, dist ) );
  30084. } );
  30085. } );
  30086. If( metric.equal( int( 0 ) ), () => {
  30087. sqdist.assign( sqrt( sqdist ) );
  30088. } );
  30089. return sqdist;
  30090. } ).setLayout( {
  30091. name: 'mx_worley_noise_float_0',
  30092. type: 'float',
  30093. inputs: [
  30094. { name: 'p', type: 'vec2' },
  30095. { name: 'jitter', type: 'float' },
  30096. { name: 'metric', type: 'int' }
  30097. ]
  30098. } );
  30099. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30100. const metric = int( metric_immutable ).toVar();
  30101. const jitter = float( jitter_immutable ).toVar();
  30102. const p = vec2( p_immutable ).toVar();
  30103. const X = int().toVar(), Y = int().toVar();
  30104. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30105. const sqdist = vec2( 1e6, 1e6 ).toVar();
  30106. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30107. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30108. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30109. If( dist.lessThan( sqdist.x ), () => {
  30110. sqdist.y.assign( sqdist.x );
  30111. sqdist.x.assign( dist );
  30112. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30113. sqdist.y.assign( dist );
  30114. } );
  30115. } );
  30116. } );
  30117. If( metric.equal( int( 0 ) ), () => {
  30118. sqdist.assign( sqrt( sqdist ) );
  30119. } );
  30120. return sqdist;
  30121. } ).setLayout( {
  30122. name: 'mx_worley_noise_vec2_0',
  30123. type: 'vec2',
  30124. inputs: [
  30125. { name: 'p', type: 'vec2' },
  30126. { name: 'jitter', type: 'float' },
  30127. { name: 'metric', type: 'int' }
  30128. ]
  30129. } );
  30130. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30131. const metric = int( metric_immutable ).toVar();
  30132. const jitter = float( jitter_immutable ).toVar();
  30133. const p = vec2( p_immutable ).toVar();
  30134. const X = int().toVar(), Y = int().toVar();
  30135. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30136. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  30137. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30138. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30139. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30140. If( dist.lessThan( sqdist.x ), () => {
  30141. sqdist.z.assign( sqdist.y );
  30142. sqdist.y.assign( sqdist.x );
  30143. sqdist.x.assign( dist );
  30144. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30145. sqdist.z.assign( sqdist.y );
  30146. sqdist.y.assign( dist );
  30147. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  30148. sqdist.z.assign( dist );
  30149. } );
  30150. } );
  30151. } );
  30152. If( metric.equal( int( 0 ) ), () => {
  30153. sqdist.assign( sqrt( sqdist ) );
  30154. } );
  30155. return sqdist;
  30156. } ).setLayout( {
  30157. name: 'mx_worley_noise_vec3_0',
  30158. type: 'vec3',
  30159. inputs: [
  30160. { name: 'p', type: 'vec2' },
  30161. { name: 'jitter', type: 'float' },
  30162. { name: 'metric', type: 'int' }
  30163. ]
  30164. } );
  30165. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30166. const metric = int( metric_immutable ).toVar();
  30167. const jitter = float( jitter_immutable ).toVar();
  30168. const p = vec3( p_immutable ).toVar();
  30169. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30170. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30171. const sqdist = float( 1e6 ).toVar();
  30172. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30173. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30174. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30175. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30176. sqdist.assign( min$1( sqdist, dist ) );
  30177. } );
  30178. } );
  30179. } );
  30180. If( metric.equal( int( 0 ) ), () => {
  30181. sqdist.assign( sqrt( sqdist ) );
  30182. } );
  30183. return sqdist;
  30184. } ).setLayout( {
  30185. name: 'mx_worley_noise_float_1',
  30186. type: 'float',
  30187. inputs: [
  30188. { name: 'p', type: 'vec3' },
  30189. { name: 'jitter', type: 'float' },
  30190. { name: 'metric', type: 'int' }
  30191. ]
  30192. } );
  30193. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  30194. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30195. const metric = int( metric_immutable ).toVar();
  30196. const jitter = float( jitter_immutable ).toVar();
  30197. const p = vec3( p_immutable ).toVar();
  30198. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30199. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30200. const sqdist = vec2( 1e6, 1e6 ).toVar();
  30201. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30202. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30203. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30204. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30205. If( dist.lessThan( sqdist.x ), () => {
  30206. sqdist.y.assign( sqdist.x );
  30207. sqdist.x.assign( dist );
  30208. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30209. sqdist.y.assign( dist );
  30210. } );
  30211. } );
  30212. } );
  30213. } );
  30214. If( metric.equal( int( 0 ) ), () => {
  30215. sqdist.assign( sqrt( sqdist ) );
  30216. } );
  30217. return sqdist;
  30218. } ).setLayout( {
  30219. name: 'mx_worley_noise_vec2_1',
  30220. type: 'vec2',
  30221. inputs: [
  30222. { name: 'p', type: 'vec3' },
  30223. { name: 'jitter', type: 'float' },
  30224. { name: 'metric', type: 'int' }
  30225. ]
  30226. } );
  30227. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  30228. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30229. const metric = int( metric_immutable ).toVar();
  30230. const jitter = float( jitter_immutable ).toVar();
  30231. const p = vec3( p_immutable ).toVar();
  30232. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30233. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30234. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  30235. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30236. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30237. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30238. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30239. If( dist.lessThan( sqdist.x ), () => {
  30240. sqdist.z.assign( sqdist.y );
  30241. sqdist.y.assign( sqdist.x );
  30242. sqdist.x.assign( dist );
  30243. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30244. sqdist.z.assign( sqdist.y );
  30245. sqdist.y.assign( dist );
  30246. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  30247. sqdist.z.assign( dist );
  30248. } );
  30249. } );
  30250. } );
  30251. } );
  30252. If( metric.equal( int( 0 ) ), () => {
  30253. sqdist.assign( sqrt( sqdist ) );
  30254. } );
  30255. return sqdist;
  30256. } ).setLayout( {
  30257. name: 'mx_worley_noise_vec3_1',
  30258. type: 'vec3',
  30259. inputs: [
  30260. { name: 'p', type: 'vec3' },
  30261. { name: 'jitter', type: 'float' },
  30262. { name: 'metric', type: 'int' }
  30263. ]
  30264. } );
  30265. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  30266. // Unified Noise 2D
  30267. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  30268. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  30269. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  30270. octaves_immutable, lacunarity_immutable, diminish_immutable
  30271. ] ) => {
  30272. const noiseType = int( noiseType_immutable ).toVar();
  30273. const texcoord = vec2( texcoord_immutable ).toVar();
  30274. const freq = vec2( freq_immutable ).toVar();
  30275. const offset = vec2( offset_immutable ).toVar();
  30276. const jitter = float( jitter_immutable ).toVar();
  30277. const outmin = float( outmin_immutable ).toVar();
  30278. const outmax = float( outmax_immutable ).toVar();
  30279. const clampoutput = bool( clampoutput_immutable ).toVar();
  30280. const octaves = int( octaves_immutable ).toVar();
  30281. const lacunarity = float( lacunarity_immutable ).toVar();
  30282. const diminish = float( diminish_immutable ).toVar();
  30283. // Compute input position
  30284. const p = texcoord.mul( freq ).add( offset );
  30285. const result = float( 0.0 ).toVar();
  30286. // Perlin
  30287. If( noiseType.equal( int( 0 ) ), () => {
  30288. result.assign( mx_perlin_noise_vec3( p ) );
  30289. } );
  30290. // Cell
  30291. If( noiseType.equal( int( 1 ) ), () => {
  30292. result.assign( mx_cell_noise_vec3( p ) );
  30293. } );
  30294. // Worley (metric=0 = euclidean)
  30295. If( noiseType.equal( int( 2 ) ), () => {
  30296. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  30297. } );
  30298. // Fractal (use vec3(p, 0.0) for 2D input)
  30299. If( noiseType.equal( int( 3 ) ), () => {
  30300. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  30301. } );
  30302. // Remap output to [outmin, outmax]
  30303. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  30304. // Clamp if requested
  30305. If( clampoutput, () => {
  30306. result.assign( clamp( result, outmin, outmax ) );
  30307. } );
  30308. return result;
  30309. } ).setLayout( {
  30310. name: 'mx_unifiednoise2d',
  30311. type: 'float',
  30312. inputs: [
  30313. { name: 'noiseType', type: 'int' },
  30314. { name: 'texcoord', type: 'vec2' },
  30315. { name: 'freq', type: 'vec2' },
  30316. { name: 'offset', type: 'vec2' },
  30317. { name: 'jitter', type: 'float' },
  30318. { name: 'outmin', type: 'float' },
  30319. { name: 'outmax', type: 'float' },
  30320. { name: 'clampoutput', type: 'bool' },
  30321. { name: 'octaves', type: 'int' },
  30322. { name: 'lacunarity', type: 'float' },
  30323. { name: 'diminish', type: 'float' }
  30324. ]
  30325. } );
  30326. // Unified Noise 3D
  30327. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  30328. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  30329. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  30330. octaves_immutable, lacunarity_immutable, diminish_immutable
  30331. ] ) => {
  30332. const noiseType = int( noiseType_immutable ).toVar();
  30333. const position = vec3( position_immutable ).toVar();
  30334. const freq = vec3( freq_immutable ).toVar();
  30335. const offset = vec3( offset_immutable ).toVar();
  30336. const jitter = float( jitter_immutable ).toVar();
  30337. const outmin = float( outmin_immutable ).toVar();
  30338. const outmax = float( outmax_immutable ).toVar();
  30339. const clampoutput = bool( clampoutput_immutable ).toVar();
  30340. const octaves = int( octaves_immutable ).toVar();
  30341. const lacunarity = float( lacunarity_immutable ).toVar();
  30342. const diminish = float( diminish_immutable ).toVar();
  30343. // Compute input position
  30344. const p = position.mul( freq ).add( offset );
  30345. const result = float( 0.0 ).toVar();
  30346. // Perlin
  30347. If( noiseType.equal( int( 0 ) ), () => {
  30348. result.assign( mx_perlin_noise_vec3( p ) );
  30349. } );
  30350. // Cell
  30351. If( noiseType.equal( int( 1 ) ), () => {
  30352. result.assign( mx_cell_noise_vec3( p ) );
  30353. } );
  30354. // Worley (metric=0 = euclidean)
  30355. If( noiseType.equal( int( 2 ) ), () => {
  30356. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  30357. } );
  30358. // Fractal
  30359. If( noiseType.equal( int( 3 ) ), () => {
  30360. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  30361. } );
  30362. // Remap output to [outmin, outmax]
  30363. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  30364. // Clamp if requested
  30365. If( clampoutput, () => {
  30366. result.assign( clamp( result, outmin, outmax ) );
  30367. } );
  30368. return result;
  30369. } ).setLayout( {
  30370. name: 'mx_unifiednoise3d',
  30371. type: 'float',
  30372. inputs: [
  30373. { name: 'noiseType', type: 'int' },
  30374. { name: 'position', type: 'vec3' },
  30375. { name: 'freq', type: 'vec3' },
  30376. { name: 'offset', type: 'vec3' },
  30377. { name: 'jitter', type: 'float' },
  30378. { name: 'outmin', type: 'float' },
  30379. { name: 'outmax', type: 'float' },
  30380. { name: 'clampoutput', type: 'bool' },
  30381. { name: 'octaves', type: 'int' },
  30382. { name: 'lacunarity', type: 'float' },
  30383. { name: 'diminish', type: 'float' }
  30384. ]
  30385. } );
  30386. // Three.js Transpiler
  30387. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  30388. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  30389. const s = hsv.y;
  30390. const v = hsv.z;
  30391. const result = vec3().toVar();
  30392. If( s.lessThan( 0.0001 ), () => {
  30393. result.assign( vec3( v, v, v ) );
  30394. } ).Else( () => {
  30395. let h = hsv.x;
  30396. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  30397. const hi = int( trunc( h ) );
  30398. const f = h.sub( float( hi ) );
  30399. const p = v.mul( s.oneMinus() );
  30400. const q = v.mul( s.mul( f ).oneMinus() );
  30401. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  30402. If( hi.equal( int( 0 ) ), () => {
  30403. result.assign( vec3( v, t, p ) );
  30404. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  30405. result.assign( vec3( q, v, p ) );
  30406. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  30407. result.assign( vec3( p, v, t ) );
  30408. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  30409. result.assign( vec3( p, q, v ) );
  30410. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  30411. result.assign( vec3( t, p, v ) );
  30412. } ).Else( () => {
  30413. result.assign( vec3( v, p, q ) );
  30414. } );
  30415. } );
  30416. return result;
  30417. } ).setLayout( {
  30418. name: 'mx_hsvtorgb',
  30419. type: 'vec3',
  30420. inputs: [
  30421. { name: 'hsv', type: 'vec3' }
  30422. ]
  30423. } );
  30424. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  30425. const c = vec3( c_immutable ).toVar();
  30426. const r = float( c.x ).toVar();
  30427. const g = float( c.y ).toVar();
  30428. const b = float( c.z ).toVar();
  30429. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  30430. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  30431. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  30432. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  30433. v.assign( maxcomp );
  30434. If( maxcomp.greaterThan( 0.0 ), () => {
  30435. s.assign( delta.div( maxcomp ) );
  30436. } ).Else( () => {
  30437. s.assign( 0.0 );
  30438. } );
  30439. If( s.lessThanEqual( 0.0 ), () => {
  30440. h.assign( 0.0 );
  30441. } ).Else( () => {
  30442. If( r.greaterThanEqual( maxcomp ), () => {
  30443. h.assign( g.sub( b ).div( delta ) );
  30444. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  30445. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  30446. } ).Else( () => {
  30447. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  30448. } );
  30449. h.mulAssign( 1.0 / 6.0 );
  30450. If( h.lessThan( 0.0 ), () => {
  30451. h.addAssign( 1.0 );
  30452. } );
  30453. } );
  30454. return vec3( h, s, v );
  30455. } ).setLayout( {
  30456. name: 'mx_rgbtohsv',
  30457. type: 'vec3',
  30458. inputs: [
  30459. { name: 'c', type: 'vec3' }
  30460. ]
  30461. } );
  30462. // Three.js Transpiler
  30463. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  30464. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  30465. const color = vec3( color_immutable ).toVar();
  30466. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  30467. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  30468. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  30469. return mix( linSeg, powSeg, isAbove );
  30470. } ).setLayout( {
  30471. name: 'mx_srgb_texture_to_lin_rec709',
  30472. type: 'vec3',
  30473. inputs: [
  30474. { name: 'color', type: 'vec3' }
  30475. ]
  30476. } );
  30477. const mx_aastep = ( threshold, value ) => {
  30478. threshold = float( threshold );
  30479. value = float( value );
  30480. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  30481. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  30482. };
  30483. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  30484. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  30485. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  30486. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  30487. const mx_ramp4 = (
  30488. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  30489. ) => {
  30490. const u = texcoord.x.clamp();
  30491. const v = texcoord.y.clamp();
  30492. const top = mix( valuetl, valuetr, u );
  30493. const bottom = mix( valuebl, valuebr, u );
  30494. return mix( top, bottom, v );
  30495. };
  30496. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  30497. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  30498. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  30499. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  30500. const mx_safepower = ( in1, in2 = 1 ) => {
  30501. in1 = float( in1 );
  30502. return in1.abs().pow( in2 ).mul( in1.sign() );
  30503. };
  30504. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  30505. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  30506. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  30507. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  30508. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  30509. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  30510. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  30511. return noise_vec4.mul( amplitude ).add( pivot );
  30512. };
  30513. const mx_unifiednoise2d = ( noiseType, texcoord = uv$1(), freq = vec2( 1, 1 ), offset = vec2( 0, 0 ), jitter = 1, outmin = 0, outmax = 1, clampoutput = false, octaves = 1, lacunarity = 2, diminish = .5 ) => mx_unifiednoise2d$1( noiseType, texcoord.convert( 'vec2|vec3' ), freq, offset, jitter, outmin, outmax, clampoutput, octaves, lacunarity, diminish );
  30514. const mx_unifiednoise3d = ( noiseType, texcoord = uv$1(), freq = vec2( 1, 1 ), offset = vec2( 0, 0 ), jitter = 1, outmin = 0, outmax = 1, clampoutput = false, octaves = 1, lacunarity = 2, diminish = .5 ) => mx_unifiednoise3d$1( noiseType, texcoord.convert( 'vec2|vec3' ), freq, offset, jitter, outmin, outmax, clampoutput, octaves, lacunarity, diminish );
  30515. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  30516. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  30517. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  30518. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  30519. const mx_fractal_noise_float = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  30520. const mx_fractal_noise_vec2 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  30521. const mx_fractal_noise_vec3 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  30522. const mx_fractal_noise_vec4 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  30523. // === Moved from MaterialXLoader.js ===
  30524. // Math ops
  30525. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  30526. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  30527. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  30528. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  30529. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  30530. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  30531. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  30532. const mx_timer = () => time;
  30533. const mx_frame = () => frameId;
  30534. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  30535. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  30536. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  30537. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  30538. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  30539. const mx_separate = ( in1, channelOrOut = null ) => {
  30540. if ( typeof channelOrOut === 'string' ) {
  30541. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  30542. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  30543. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  30544. }
  30545. if ( typeof channelOrOut === 'number' ) {
  30546. return in1.element( channelOrOut );
  30547. }
  30548. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  30549. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  30550. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  30551. }
  30552. return in1;
  30553. };
  30554. const mx_place2d = (
  30555. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  30556. ) => {
  30557. let uv = texcoord;
  30558. if ( pivot ) uv = uv.sub( pivot );
  30559. if ( scale ) uv = uv.mul( scale );
  30560. if ( rotate ) {
  30561. const rad = rotate.mul( Math.PI / 180.0 );
  30562. const cosR = rad.cos();
  30563. const sinR = rad.sin();
  30564. uv = vec2(
  30565. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  30566. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  30567. );
  30568. }
  30569. if ( pivot ) uv = uv.add( pivot );
  30570. if ( offset ) uv = uv.add( offset );
  30571. return uv;
  30572. };
  30573. const mx_rotate2d = ( input, amount ) => {
  30574. input = vec2( input );
  30575. amount = float( amount );
  30576. const radians = amount.mul( Math.PI / 180.0 );
  30577. return rotate( input, radians );
  30578. };
  30579. const mx_rotate3d = ( input, amount, axis ) => {
  30580. input = vec3( input );
  30581. amount = float( amount );
  30582. axis = vec3( axis );
  30583. const radians = amount.mul( Math.PI / 180.0 );
  30584. const nAxis = axis.normalize();
  30585. const cosA = radians.cos();
  30586. const sinA = radians.sin();
  30587. const oneMinusCosA = float( 1 ).sub( cosA );
  30588. const rot =
  30589. input.mul( cosA )
  30590. .add( nAxis.cross( input ).mul( sinA ) )
  30591. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  30592. return rot;
  30593. };
  30594. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  30595. input = vec3( input );
  30596. scale = float( scale );
  30597. return bumpMap( input, scale );
  30598. };
  30599. /**
  30600. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  30601. *
  30602. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  30603. *
  30604. * ```js
  30605. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  30606. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  30607. * ```
  30608. *
  30609. * @tsl
  30610. * @function
  30611. * @param {Node<vec3>} normal - The normal to correct.
  30612. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  30613. * @param {Node<vec3>} cubePos - The cube position.
  30614. * @return {Node<vec3>} The parallax corrected normal.
  30615. */
  30616. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  30617. const nDir = normalize( normal ).toVar();
  30618. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  30619. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  30620. const rbminmax = vec3().toVar();
  30621. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  30622. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  30623. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  30624. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  30625. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  30626. return boxIntersection.sub( cubePos );
  30627. } );
  30628. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  30629. // normal is assumed to have unit length
  30630. const x = normal.x, y = normal.y, z = normal.z;
  30631. // band 0
  30632. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  30633. // band 1
  30634. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  30635. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  30636. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  30637. // band 2
  30638. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  30639. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  30640. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  30641. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  30642. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  30643. return result;
  30644. } );
  30645. // constants
  30646. var TSL = /*#__PURE__*/Object.freeze({
  30647. __proto__: null,
  30648. BRDF_GGX: BRDF_GGX,
  30649. BRDF_Lambert: BRDF_Lambert,
  30650. BasicPointShadowFilter: BasicPointShadowFilter,
  30651. BasicShadowFilter: BasicShadowFilter,
  30652. Break: Break,
  30653. Const: Const,
  30654. Continue: Continue,
  30655. DFGApprox: DFGApprox,
  30656. D_GGX: D_GGX,
  30657. Discard: Discard,
  30658. EPSILON: EPSILON,
  30659. F_Schlick: F_Schlick,
  30660. Fn: Fn,
  30661. INFINITY: INFINITY,
  30662. If: If,
  30663. Loop: Loop,
  30664. NodeAccess: NodeAccess,
  30665. NodeShaderStage: NodeShaderStage,
  30666. NodeType: NodeType,
  30667. NodeUpdateType: NodeUpdateType,
  30668. OnMaterialUpdate: OnMaterialUpdate,
  30669. OnObjectUpdate: OnObjectUpdate,
  30670. PCFShadowFilter: PCFShadowFilter,
  30671. PCFSoftShadowFilter: PCFSoftShadowFilter,
  30672. PI: PI,
  30673. PI2: PI2,
  30674. PointShadowFilter: PointShadowFilter,
  30675. Return: Return,
  30676. Schlick_to_F0: Schlick_to_F0,
  30677. ScriptableNodeResources: ScriptableNodeResources,
  30678. ShaderNode: ShaderNode,
  30679. Stack: Stack,
  30680. Switch: Switch,
  30681. TBNViewMatrix: TBNViewMatrix,
  30682. VSMShadowFilter: VSMShadowFilter,
  30683. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  30684. Var: Var,
  30685. VarIntent: VarIntent,
  30686. abs: abs,
  30687. acesFilmicToneMapping: acesFilmicToneMapping,
  30688. acos: acos,
  30689. add: add,
  30690. addMethodChaining: addMethodChaining,
  30691. addNodeElement: addNodeElement,
  30692. agxToneMapping: agxToneMapping,
  30693. all: all,
  30694. alphaT: alphaT,
  30695. and: and,
  30696. anisotropy: anisotropy,
  30697. anisotropyB: anisotropyB,
  30698. anisotropyT: anisotropyT,
  30699. any: any,
  30700. append: append,
  30701. array: array,
  30702. arrayBuffer: arrayBuffer,
  30703. asin: asin,
  30704. assign: assign,
  30705. atan: atan,
  30706. atan2: atan2,
  30707. atomicAdd: atomicAdd,
  30708. atomicAnd: atomicAnd,
  30709. atomicFunc: atomicFunc,
  30710. atomicLoad: atomicLoad,
  30711. atomicMax: atomicMax,
  30712. atomicMin: atomicMin,
  30713. atomicOr: atomicOr,
  30714. atomicStore: atomicStore,
  30715. atomicSub: atomicSub,
  30716. atomicXor: atomicXor,
  30717. attenuationColor: attenuationColor,
  30718. attenuationDistance: attenuationDistance,
  30719. attribute: attribute,
  30720. attributeArray: attributeArray,
  30721. backgroundBlurriness: backgroundBlurriness,
  30722. backgroundIntensity: backgroundIntensity,
  30723. backgroundRotation: backgroundRotation,
  30724. batch: batch,
  30725. bentNormalView: bentNormalView,
  30726. billboarding: billboarding,
  30727. bitAnd: bitAnd,
  30728. bitNot: bitNot,
  30729. bitOr: bitOr,
  30730. bitXor: bitXor,
  30731. bitangentGeometry: bitangentGeometry,
  30732. bitangentLocal: bitangentLocal,
  30733. bitangentView: bitangentView,
  30734. bitangentWorld: bitangentWorld,
  30735. bitcast: bitcast,
  30736. blendBurn: blendBurn,
  30737. blendColor: blendColor,
  30738. blendDodge: blendDodge,
  30739. blendOverlay: blendOverlay,
  30740. blendScreen: blendScreen,
  30741. blur: blur,
  30742. bool: bool,
  30743. buffer: buffer,
  30744. bufferAttribute: bufferAttribute,
  30745. bumpMap: bumpMap,
  30746. burn: burn,
  30747. bvec2: bvec2,
  30748. bvec3: bvec3,
  30749. bvec4: bvec4,
  30750. bypass: bypass,
  30751. cache: cache,
  30752. call: call,
  30753. cameraFar: cameraFar,
  30754. cameraIndex: cameraIndex,
  30755. cameraNear: cameraNear,
  30756. cameraNormalMatrix: cameraNormalMatrix,
  30757. cameraPosition: cameraPosition,
  30758. cameraProjectionMatrix: cameraProjectionMatrix,
  30759. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  30760. cameraViewMatrix: cameraViewMatrix,
  30761. cameraWorldMatrix: cameraWorldMatrix,
  30762. cbrt: cbrt,
  30763. cdl: cdl,
  30764. ceil: ceil,
  30765. checker: checker,
  30766. cineonToneMapping: cineonToneMapping,
  30767. clamp: clamp,
  30768. clearcoat: clearcoat,
  30769. clearcoatNormalView: clearcoatNormalView,
  30770. clearcoatRoughness: clearcoatRoughness,
  30771. code: code,
  30772. color: color,
  30773. colorSpaceToWorking: colorSpaceToWorking,
  30774. colorToDirection: colorToDirection,
  30775. compute: compute,
  30776. computeKernel: computeKernel,
  30777. computeSkinning: computeSkinning,
  30778. context: context,
  30779. convert: convert,
  30780. convertColorSpace: convertColorSpace,
  30781. convertToTexture: convertToTexture,
  30782. cos: cos,
  30783. cross: cross,
  30784. cubeTexture: cubeTexture,
  30785. cubeTextureBase: cubeTextureBase,
  30786. cubeToUV: cubeToUV,
  30787. dFdx: dFdx,
  30788. dFdy: dFdy,
  30789. dashSize: dashSize,
  30790. debug: debug,
  30791. decrement: decrement,
  30792. decrementBefore: decrementBefore,
  30793. defaultBuildStages: defaultBuildStages,
  30794. defaultShaderStages: defaultShaderStages,
  30795. defined: defined,
  30796. degrees: degrees,
  30797. deltaTime: deltaTime,
  30798. densityFog: densityFog,
  30799. densityFogFactor: densityFogFactor,
  30800. depth: depth,
  30801. depthPass: depthPass,
  30802. determinant: determinant,
  30803. difference: difference,
  30804. diffuseColor: diffuseColor,
  30805. directPointLight: directPointLight,
  30806. directionToColor: directionToColor,
  30807. directionToFaceDirection: directionToFaceDirection,
  30808. dispersion: dispersion,
  30809. distance: distance,
  30810. div: div,
  30811. dodge: dodge,
  30812. dot: dot,
  30813. drawIndex: drawIndex,
  30814. dynamicBufferAttribute: dynamicBufferAttribute,
  30815. element: element,
  30816. emissive: emissive,
  30817. equal: equal,
  30818. equals: equals,
  30819. equirectUV: equirectUV,
  30820. exp: exp,
  30821. exp2: exp2,
  30822. expression: expression,
  30823. faceDirection: faceDirection,
  30824. faceForward: faceForward,
  30825. faceforward: faceforward,
  30826. float: float,
  30827. floor: floor,
  30828. fog: fog,
  30829. fract: fract,
  30830. frameGroup: frameGroup,
  30831. frameId: frameId,
  30832. frontFacing: frontFacing,
  30833. fwidth: fwidth,
  30834. gain: gain,
  30835. gapSize: gapSize,
  30836. getConstNodeType: getConstNodeType,
  30837. getCurrentStack: getCurrentStack,
  30838. getDirection: getDirection,
  30839. getDistanceAttenuation: getDistanceAttenuation,
  30840. getGeometryRoughness: getGeometryRoughness,
  30841. getNormalFromDepth: getNormalFromDepth,
  30842. getParallaxCorrectNormal: getParallaxCorrectNormal,
  30843. getRoughness: getRoughness,
  30844. getScreenPosition: getScreenPosition,
  30845. getShIrradianceAt: getShIrradianceAt,
  30846. getShadowMaterial: getShadowMaterial,
  30847. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  30848. getTextureIndex: getTextureIndex,
  30849. getViewPosition: getViewPosition,
  30850. globalId: globalId,
  30851. glsl: glsl,
  30852. glslFn: glslFn,
  30853. grayscale: grayscale,
  30854. greaterThan: greaterThan,
  30855. greaterThanEqual: greaterThanEqual,
  30856. hash: hash,
  30857. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  30858. highpModelViewMatrix: highpModelViewMatrix,
  30859. hue: hue,
  30860. increment: increment,
  30861. incrementBefore: incrementBefore,
  30862. instance: instance,
  30863. instanceIndex: instanceIndex,
  30864. instancedArray: instancedArray,
  30865. instancedBufferAttribute: instancedBufferAttribute,
  30866. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  30867. instancedMesh: instancedMesh,
  30868. int: int,
  30869. inverse: inverse,
  30870. inverseSqrt: inverseSqrt,
  30871. inversesqrt: inversesqrt,
  30872. invocationLocalIndex: invocationLocalIndex,
  30873. invocationSubgroupIndex: invocationSubgroupIndex,
  30874. ior: ior,
  30875. iridescence: iridescence,
  30876. iridescenceIOR: iridescenceIOR,
  30877. iridescenceThickness: iridescenceThickness,
  30878. ivec2: ivec2,
  30879. ivec3: ivec3,
  30880. ivec4: ivec4,
  30881. js: js,
  30882. label: label,
  30883. length: length,
  30884. lengthSq: lengthSq,
  30885. lessThan: lessThan,
  30886. lessThanEqual: lessThanEqual,
  30887. lightPosition: lightPosition,
  30888. lightProjectionUV: lightProjectionUV,
  30889. lightShadowMatrix: lightShadowMatrix,
  30890. lightTargetDirection: lightTargetDirection,
  30891. lightTargetPosition: lightTargetPosition,
  30892. lightViewPosition: lightViewPosition,
  30893. lightingContext: lightingContext,
  30894. lights: lights,
  30895. linearDepth: linearDepth,
  30896. linearToneMapping: linearToneMapping,
  30897. localId: localId,
  30898. log: log,
  30899. log2: log2,
  30900. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  30901. luminance: luminance,
  30902. mat2: mat2,
  30903. mat3: mat3,
  30904. mat4: mat4,
  30905. matcapUV: matcapUV,
  30906. materialAO: materialAO,
  30907. materialAlphaTest: materialAlphaTest,
  30908. materialAnisotropy: materialAnisotropy,
  30909. materialAnisotropyVector: materialAnisotropyVector,
  30910. materialAttenuationColor: materialAttenuationColor,
  30911. materialAttenuationDistance: materialAttenuationDistance,
  30912. materialClearcoat: materialClearcoat,
  30913. materialClearcoatNormal: materialClearcoatNormal,
  30914. materialClearcoatRoughness: materialClearcoatRoughness,
  30915. materialColor: materialColor,
  30916. materialDispersion: materialDispersion,
  30917. materialEmissive: materialEmissive,
  30918. materialEnvIntensity: materialEnvIntensity,
  30919. materialEnvRotation: materialEnvRotation,
  30920. materialIOR: materialIOR,
  30921. materialIridescence: materialIridescence,
  30922. materialIridescenceIOR: materialIridescenceIOR,
  30923. materialIridescenceThickness: materialIridescenceThickness,
  30924. materialLightMap: materialLightMap,
  30925. materialLineDashOffset: materialLineDashOffset,
  30926. materialLineDashSize: materialLineDashSize,
  30927. materialLineGapSize: materialLineGapSize,
  30928. materialLineScale: materialLineScale,
  30929. materialLineWidth: materialLineWidth,
  30930. materialMetalness: materialMetalness,
  30931. materialNormal: materialNormal,
  30932. materialOpacity: materialOpacity,
  30933. materialPointSize: materialPointSize,
  30934. materialReference: materialReference,
  30935. materialReflectivity: materialReflectivity,
  30936. materialRefractionRatio: materialRefractionRatio,
  30937. materialRotation: materialRotation,
  30938. materialRoughness: materialRoughness,
  30939. materialSheen: materialSheen,
  30940. materialSheenRoughness: materialSheenRoughness,
  30941. materialShininess: materialShininess,
  30942. materialSpecular: materialSpecular,
  30943. materialSpecularColor: materialSpecularColor,
  30944. materialSpecularIntensity: materialSpecularIntensity,
  30945. materialSpecularStrength: materialSpecularStrength,
  30946. materialThickness: materialThickness,
  30947. materialTransmission: materialTransmission,
  30948. max: max$1,
  30949. maxMipLevel: maxMipLevel,
  30950. mediumpModelViewMatrix: mediumpModelViewMatrix,
  30951. metalness: metalness,
  30952. min: min$1,
  30953. mix: mix,
  30954. mixElement: mixElement,
  30955. mod: mod,
  30956. modInt: modInt,
  30957. modelDirection: modelDirection,
  30958. modelNormalMatrix: modelNormalMatrix,
  30959. modelPosition: modelPosition,
  30960. modelRadius: modelRadius,
  30961. modelScale: modelScale,
  30962. modelViewMatrix: modelViewMatrix,
  30963. modelViewPosition: modelViewPosition,
  30964. modelViewProjection: modelViewProjection,
  30965. modelWorldMatrix: modelWorldMatrix,
  30966. modelWorldMatrixInverse: modelWorldMatrixInverse,
  30967. morphReference: morphReference,
  30968. mrt: mrt,
  30969. mul: mul,
  30970. mx_aastep: mx_aastep,
  30971. mx_add: mx_add,
  30972. mx_atan2: mx_atan2,
  30973. mx_cell_noise_float: mx_cell_noise_float,
  30974. mx_contrast: mx_contrast,
  30975. mx_divide: mx_divide,
  30976. mx_fractal_noise_float: mx_fractal_noise_float,
  30977. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  30978. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  30979. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  30980. mx_frame: mx_frame,
  30981. mx_heighttonormal: mx_heighttonormal,
  30982. mx_hsvtorgb: mx_hsvtorgb,
  30983. mx_ifequal: mx_ifequal,
  30984. mx_ifgreater: mx_ifgreater,
  30985. mx_ifgreatereq: mx_ifgreatereq,
  30986. mx_invert: mx_invert,
  30987. mx_modulo: mx_modulo,
  30988. mx_multiply: mx_multiply,
  30989. mx_noise_float: mx_noise_float,
  30990. mx_noise_vec3: mx_noise_vec3,
  30991. mx_noise_vec4: mx_noise_vec4,
  30992. mx_place2d: mx_place2d,
  30993. mx_power: mx_power,
  30994. mx_ramp4: mx_ramp4,
  30995. mx_ramplr: mx_ramplr,
  30996. mx_ramptb: mx_ramptb,
  30997. mx_rgbtohsv: mx_rgbtohsv,
  30998. mx_rotate2d: mx_rotate2d,
  30999. mx_rotate3d: mx_rotate3d,
  31000. mx_safepower: mx_safepower,
  31001. mx_separate: mx_separate,
  31002. mx_splitlr: mx_splitlr,
  31003. mx_splittb: mx_splittb,
  31004. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  31005. mx_subtract: mx_subtract,
  31006. mx_timer: mx_timer,
  31007. mx_transform_uv: mx_transform_uv,
  31008. mx_unifiednoise2d: mx_unifiednoise2d,
  31009. mx_unifiednoise3d: mx_unifiednoise3d,
  31010. mx_worley_noise_float: mx_worley_noise_float,
  31011. mx_worley_noise_vec2: mx_worley_noise_vec2,
  31012. mx_worley_noise_vec3: mx_worley_noise_vec3,
  31013. negate: negate,
  31014. neutralToneMapping: neutralToneMapping,
  31015. nodeArray: nodeArray,
  31016. nodeImmutable: nodeImmutable,
  31017. nodeObject: nodeObject,
  31018. nodeObjectIntent: nodeObjectIntent,
  31019. nodeObjects: nodeObjects,
  31020. nodeProxy: nodeProxy,
  31021. nodeProxyIntent: nodeProxyIntent,
  31022. normalFlat: normalFlat,
  31023. normalGeometry: normalGeometry,
  31024. normalLocal: normalLocal,
  31025. normalMap: normalMap,
  31026. normalView: normalView,
  31027. normalViewGeometry: normalViewGeometry,
  31028. normalWorld: normalWorld,
  31029. normalWorldGeometry: normalWorldGeometry,
  31030. normalize: normalize,
  31031. not: not,
  31032. notEqual: notEqual,
  31033. numWorkgroups: numWorkgroups,
  31034. objectDirection: objectDirection,
  31035. objectGroup: objectGroup,
  31036. objectPosition: objectPosition,
  31037. objectRadius: objectRadius,
  31038. objectScale: objectScale,
  31039. objectViewPosition: objectViewPosition,
  31040. objectWorldMatrix: objectWorldMatrix,
  31041. oneMinus: oneMinus,
  31042. or: or,
  31043. orthographicDepthToViewZ: orthographicDepthToViewZ,
  31044. oscSawtooth: oscSawtooth,
  31045. oscSine: oscSine,
  31046. oscSquare: oscSquare,
  31047. oscTriangle: oscTriangle,
  31048. output: output,
  31049. outputStruct: outputStruct,
  31050. overlay: overlay,
  31051. overloadingFn: overloadingFn,
  31052. parabola: parabola,
  31053. parallaxDirection: parallaxDirection,
  31054. parallaxUV: parallaxUV,
  31055. parameter: parameter,
  31056. pass: pass,
  31057. passTexture: passTexture,
  31058. pcurve: pcurve,
  31059. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  31060. pmremTexture: pmremTexture,
  31061. pointShadow: pointShadow,
  31062. pointUV: pointUV,
  31063. pointWidth: pointWidth,
  31064. positionGeometry: positionGeometry,
  31065. positionLocal: positionLocal,
  31066. positionPrevious: positionPrevious,
  31067. positionView: positionView,
  31068. positionViewDirection: positionViewDirection,
  31069. positionWorld: positionWorld,
  31070. positionWorldDirection: positionWorldDirection,
  31071. posterize: posterize,
  31072. pow: pow,
  31073. pow2: pow2,
  31074. pow3: pow3,
  31075. pow4: pow4,
  31076. premultiplyAlpha: premultiplyAlpha,
  31077. property: property,
  31078. radians: radians,
  31079. rand: rand,
  31080. range: range,
  31081. rangeFog: rangeFog,
  31082. rangeFogFactor: rangeFogFactor,
  31083. reciprocal: reciprocal,
  31084. reference: reference,
  31085. referenceBuffer: referenceBuffer,
  31086. reflect: reflect,
  31087. reflectVector: reflectVector,
  31088. reflectView: reflectView,
  31089. reflector: reflector,
  31090. refract: refract,
  31091. refractVector: refractVector,
  31092. refractView: refractView,
  31093. reinhardToneMapping: reinhardToneMapping,
  31094. remap: remap,
  31095. remapClamp: remapClamp,
  31096. renderGroup: renderGroup,
  31097. renderOutput: renderOutput,
  31098. rendererReference: rendererReference,
  31099. rotate: rotate,
  31100. rotateUV: rotateUV,
  31101. roughness: roughness,
  31102. round: round,
  31103. rtt: rtt,
  31104. sRGBTransferEOTF: sRGBTransferEOTF,
  31105. sRGBTransferOETF: sRGBTransferOETF,
  31106. sample: sample,
  31107. sampler: sampler,
  31108. samplerComparison: samplerComparison,
  31109. saturate: saturate,
  31110. saturation: saturation,
  31111. screen: screen,
  31112. screenCoordinate: screenCoordinate,
  31113. screenSize: screenSize,
  31114. screenUV: screenUV,
  31115. scriptable: scriptable,
  31116. scriptableValue: scriptableValue,
  31117. select: select,
  31118. setCurrentStack: setCurrentStack,
  31119. shaderStages: shaderStages,
  31120. shadow: shadow,
  31121. shadowPositionWorld: shadowPositionWorld,
  31122. shapeCircle: shapeCircle,
  31123. sharedUniformGroup: sharedUniformGroup,
  31124. sheen: sheen,
  31125. sheenRoughness: sheenRoughness,
  31126. shiftLeft: shiftLeft,
  31127. shiftRight: shiftRight,
  31128. shininess: shininess,
  31129. sign: sign,
  31130. sin: sin,
  31131. sinc: sinc,
  31132. skinning: skinning,
  31133. smoothstep: smoothstep,
  31134. smoothstepElement: smoothstepElement,
  31135. specularColor: specularColor,
  31136. specularF90: specularF90,
  31137. spherizeUV: spherizeUV,
  31138. split: split,
  31139. spritesheetUV: spritesheetUV,
  31140. sqrt: sqrt,
  31141. stack: stack,
  31142. step: step,
  31143. stepElement: stepElement,
  31144. storage: storage,
  31145. storageBarrier: storageBarrier,
  31146. storageObject: storageObject,
  31147. storageTexture: storageTexture,
  31148. string: string,
  31149. struct: struct,
  31150. sub: sub,
  31151. subBuild: subBuild,
  31152. subgroupIndex: subgroupIndex,
  31153. subgroupSize: subgroupSize,
  31154. tan: tan,
  31155. tangentGeometry: tangentGeometry,
  31156. tangentLocal: tangentLocal,
  31157. tangentView: tangentView,
  31158. tangentWorld: tangentWorld,
  31159. temp: temp,
  31160. texture: texture,
  31161. texture3D: texture3D,
  31162. textureBarrier: textureBarrier,
  31163. textureBicubic: textureBicubic,
  31164. textureBicubicLevel: textureBicubicLevel,
  31165. textureCubeUV: textureCubeUV,
  31166. textureLoad: textureLoad,
  31167. textureSize: textureSize,
  31168. textureStore: textureStore,
  31169. thickness: thickness,
  31170. time: time,
  31171. timerDelta: timerDelta,
  31172. timerGlobal: timerGlobal,
  31173. timerLocal: timerLocal,
  31174. toneMapping: toneMapping,
  31175. toneMappingExposure: toneMappingExposure,
  31176. toonOutlinePass: toonOutlinePass,
  31177. transformDirection: transformDirection,
  31178. transformNormal: transformNormal,
  31179. transformNormalToView: transformNormalToView,
  31180. transformedClearcoatNormalView: transformedClearcoatNormalView,
  31181. transformedNormalView: transformedNormalView,
  31182. transformedNormalWorld: transformedNormalWorld,
  31183. transmission: transmission,
  31184. transpose: transpose,
  31185. triNoise3D: triNoise3D,
  31186. triplanarTexture: triplanarTexture,
  31187. triplanarTextures: triplanarTextures,
  31188. trunc: trunc,
  31189. uint: uint,
  31190. uniform: uniform,
  31191. uniformArray: uniformArray,
  31192. uniformCubeTexture: uniformCubeTexture,
  31193. uniformGroup: uniformGroup,
  31194. uniformTexture: uniformTexture,
  31195. unpremultiplyAlpha: unpremultiplyAlpha,
  31196. userData: userData,
  31197. uv: uv$1,
  31198. uvec2: uvec2,
  31199. uvec3: uvec3,
  31200. uvec4: uvec4,
  31201. varying: varying,
  31202. varyingProperty: varyingProperty,
  31203. vec2: vec2,
  31204. vec3: vec3,
  31205. vec4: vec4,
  31206. vectorComponents: vectorComponents,
  31207. velocity: velocity,
  31208. vertexColor: vertexColor,
  31209. vertexIndex: vertexIndex,
  31210. vertexStage: vertexStage,
  31211. vibrance: vibrance,
  31212. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  31213. viewZToOrthographicDepth: viewZToOrthographicDepth,
  31214. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  31215. viewport: viewport,
  31216. viewportCoordinate: viewportCoordinate,
  31217. viewportDepthTexture: viewportDepthTexture,
  31218. viewportLinearDepth: viewportLinearDepth,
  31219. viewportMipTexture: viewportMipTexture,
  31220. viewportResolution: viewportResolution,
  31221. viewportSafeUV: viewportSafeUV,
  31222. viewportSharedTexture: viewportSharedTexture,
  31223. viewportSize: viewportSize,
  31224. viewportTexture: viewportTexture,
  31225. viewportUV: viewportUV,
  31226. wgsl: wgsl,
  31227. wgslFn: wgslFn,
  31228. workgroupArray: workgroupArray,
  31229. workgroupBarrier: workgroupBarrier,
  31230. workgroupId: workgroupId,
  31231. workingToColorSpace: workingToColorSpace,
  31232. xor: xor
  31233. });
  31234. const _clearColor = /*@__PURE__*/ new Color4();
  31235. /**
  31236. * This renderer module manages the background.
  31237. *
  31238. * @private
  31239. * @augments DataMap
  31240. */
  31241. class Background extends DataMap {
  31242. /**
  31243. * Constructs a new background management component.
  31244. *
  31245. * @param {Renderer} renderer - The renderer.
  31246. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  31247. */
  31248. constructor( renderer, nodes ) {
  31249. super();
  31250. /**
  31251. * The renderer.
  31252. *
  31253. * @type {Renderer}
  31254. */
  31255. this.renderer = renderer;
  31256. /**
  31257. * Renderer component for managing nodes related logic.
  31258. *
  31259. * @type {Nodes}
  31260. */
  31261. this.nodes = nodes;
  31262. }
  31263. /**
  31264. * Updates the background for the given scene. Depending on how `Scene.background`
  31265. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  31266. * or add a mesh to the render list for rendering the background as a textured plane
  31267. * or skybox.
  31268. *
  31269. * @param {Scene} scene - The scene.
  31270. * @param {RenderList} renderList - The current render list.
  31271. * @param {RenderContext} renderContext - The current render context.
  31272. */
  31273. update( scene, renderList, renderContext ) {
  31274. const renderer = this.renderer;
  31275. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  31276. let forceClear = false;
  31277. if ( background === null ) {
  31278. // no background settings, use clear color configuration from the renderer
  31279. renderer._clearColor.getRGB( _clearColor );
  31280. _clearColor.a = renderer._clearColor.a;
  31281. } else if ( background.isColor === true ) {
  31282. // background is an opaque color
  31283. background.getRGB( _clearColor );
  31284. _clearColor.a = 1;
  31285. forceClear = true;
  31286. } else if ( background.isNode === true ) {
  31287. const sceneData = this.get( scene );
  31288. const backgroundNode = background;
  31289. _clearColor.copy( renderer._clearColor );
  31290. let backgroundMesh = sceneData.backgroundMesh;
  31291. if ( backgroundMesh === undefined ) {
  31292. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  31293. // @TODO: Add Texture2D support using node context
  31294. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  31295. getTextureLevel: () => backgroundBlurriness
  31296. } );
  31297. let viewProj = modelViewProjection;
  31298. viewProj = viewProj.setZ( viewProj.w );
  31299. const nodeMaterial = new NodeMaterial();
  31300. nodeMaterial.name = 'Background.material';
  31301. nodeMaterial.side = BackSide;
  31302. nodeMaterial.depthTest = false;
  31303. nodeMaterial.depthWrite = false;
  31304. nodeMaterial.allowOverride = false;
  31305. nodeMaterial.fog = false;
  31306. nodeMaterial.lights = false;
  31307. nodeMaterial.vertexNode = viewProj;
  31308. nodeMaterial.colorNode = backgroundMeshNode;
  31309. sceneData.backgroundMeshNode = backgroundMeshNode;
  31310. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  31311. backgroundMesh.frustumCulled = false;
  31312. backgroundMesh.name = 'Background.mesh';
  31313. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  31314. this.matrixWorld.copyPosition( camera.matrixWorld );
  31315. };
  31316. function onBackgroundDispose() {
  31317. background.removeEventListener( 'dispose', onBackgroundDispose );
  31318. backgroundMesh.material.dispose();
  31319. backgroundMesh.geometry.dispose();
  31320. }
  31321. background.addEventListener( 'dispose', onBackgroundDispose );
  31322. }
  31323. const backgroundCacheKey = backgroundNode.getCacheKey();
  31324. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  31325. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  31326. sceneData.backgroundMeshNode.needsUpdate = true;
  31327. backgroundMesh.material.needsUpdate = true;
  31328. sceneData.backgroundCacheKey = backgroundCacheKey;
  31329. }
  31330. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  31331. } else {
  31332. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  31333. }
  31334. //
  31335. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  31336. if ( environmentBlendMode === 'additive' ) {
  31337. _clearColor.set( 0, 0, 0, 1 );
  31338. } else if ( environmentBlendMode === 'alpha-blend' ) {
  31339. _clearColor.set( 0, 0, 0, 0 );
  31340. }
  31341. //
  31342. if ( renderer.autoClear === true || forceClear === true ) {
  31343. const clearColorValue = renderContext.clearColorValue;
  31344. clearColorValue.r = _clearColor.r;
  31345. clearColorValue.g = _clearColor.g;
  31346. clearColorValue.b = _clearColor.b;
  31347. clearColorValue.a = _clearColor.a;
  31348. // premultiply alpha
  31349. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  31350. clearColorValue.r *= clearColorValue.a;
  31351. clearColorValue.g *= clearColorValue.a;
  31352. clearColorValue.b *= clearColorValue.a;
  31353. }
  31354. //
  31355. renderContext.depthClearValue = renderer._clearDepth;
  31356. renderContext.stencilClearValue = renderer._clearStencil;
  31357. renderContext.clearColor = renderer.autoClearColor === true;
  31358. renderContext.clearDepth = renderer.autoClearDepth === true;
  31359. renderContext.clearStencil = renderer.autoClearStencil === true;
  31360. } else {
  31361. renderContext.clearColor = false;
  31362. renderContext.clearDepth = false;
  31363. renderContext.clearStencil = false;
  31364. }
  31365. }
  31366. }
  31367. let _id$6 = 0;
  31368. /**
  31369. * A bind group represents a collection of bindings and thus a collection
  31370. * or resources. Bind groups are assigned to pipelines to provide them
  31371. * with the required resources (like uniform buffers or textures).
  31372. *
  31373. * @private
  31374. */
  31375. class BindGroup {
  31376. /**
  31377. * Constructs a new bind group.
  31378. *
  31379. * @param {string} name - The bind group's name.
  31380. * @param {Array<Binding>} bindings - An array of bindings.
  31381. * @param {number} index - The group index.
  31382. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  31383. */
  31384. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  31385. /**
  31386. * The bind group's name.
  31387. *
  31388. * @type {string}
  31389. */
  31390. this.name = name;
  31391. /**
  31392. * An array of bindings.
  31393. *
  31394. * @type {Array<Binding>}
  31395. */
  31396. this.bindings = bindings;
  31397. /**
  31398. * The group index.
  31399. *
  31400. * @type {number}
  31401. */
  31402. this.index = index;
  31403. /**
  31404. * An array of reference bindings.
  31405. *
  31406. * @type {Array<Binding>}
  31407. */
  31408. this.bindingsReference = bindingsReference;
  31409. /**
  31410. * The group's ID.
  31411. *
  31412. * @type {number}
  31413. */
  31414. this.id = _id$6 ++;
  31415. }
  31416. }
  31417. /**
  31418. * This module represents the state of a node builder after it was
  31419. * used to build the nodes for a render object. The state holds the
  31420. * results of the build for further processing in the renderer.
  31421. *
  31422. * Render objects with identical cache keys share the same node builder state.
  31423. *
  31424. * @private
  31425. */
  31426. class NodeBuilderState {
  31427. /**
  31428. * Constructs a new node builder state.
  31429. *
  31430. * @param {string} vertexShader - The native vertex shader code.
  31431. * @param {string} fragmentShader - The native fragment shader code.
  31432. * @param {string} computeShader - The native compute shader code.
  31433. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  31434. * @param {Array<BindGroup>} bindings - An array of bind groups.
  31435. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  31436. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  31437. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  31438. * @param {NodeMaterialObserver} observer - A node material observer.
  31439. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  31440. */
  31441. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  31442. /**
  31443. * The native vertex shader code.
  31444. *
  31445. * @type {string}
  31446. */
  31447. this.vertexShader = vertexShader;
  31448. /**
  31449. * The native fragment shader code.
  31450. *
  31451. * @type {string}
  31452. */
  31453. this.fragmentShader = fragmentShader;
  31454. /**
  31455. * The native compute shader code.
  31456. *
  31457. * @type {string}
  31458. */
  31459. this.computeShader = computeShader;
  31460. /**
  31461. * An array with transform attribute objects.
  31462. * Only relevant when using compute shaders with WebGL 2.
  31463. *
  31464. * @type {Array<Object>}
  31465. */
  31466. this.transforms = transforms;
  31467. /**
  31468. * An array of node attributes representing
  31469. * the attributes of the shaders.
  31470. *
  31471. * @type {Array<NodeAttribute>}
  31472. */
  31473. this.nodeAttributes = nodeAttributes;
  31474. /**
  31475. * An array of bind groups representing the uniform or storage
  31476. * buffers, texture or samplers of the shader.
  31477. *
  31478. * @type {Array<BindGroup>}
  31479. */
  31480. this.bindings = bindings;
  31481. /**
  31482. * An array of nodes that implement their `update()` method.
  31483. *
  31484. * @type {Array<Node>}
  31485. */
  31486. this.updateNodes = updateNodes;
  31487. /**
  31488. * An array of nodes that implement their `updateBefore()` method.
  31489. *
  31490. * @type {Array<Node>}
  31491. */
  31492. this.updateBeforeNodes = updateBeforeNodes;
  31493. /**
  31494. * An array of nodes that implement their `updateAfter()` method.
  31495. *
  31496. * @type {Array<Node>}
  31497. */
  31498. this.updateAfterNodes = updateAfterNodes;
  31499. /**
  31500. * A node material observer.
  31501. *
  31502. * @type {NodeMaterialObserver}
  31503. */
  31504. this.observer = observer;
  31505. /**
  31506. * How often this state is used by render objects.
  31507. *
  31508. * @type {number}
  31509. */
  31510. this.usedTimes = 0;
  31511. }
  31512. /**
  31513. * This method is used to create a array of bind groups based
  31514. * on the existing bind groups of this state. Shared groups are
  31515. * not cloned.
  31516. *
  31517. * @return {Array<BindGroup>} A array of bind groups.
  31518. */
  31519. createBindings() {
  31520. const bindings = [];
  31521. for ( const instanceGroup of this.bindings ) {
  31522. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  31523. if ( shared !== true ) {
  31524. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  31525. bindings.push( bindingsGroup );
  31526. for ( const instanceBinding of instanceGroup.bindings ) {
  31527. bindingsGroup.bindings.push( instanceBinding.clone() );
  31528. }
  31529. } else {
  31530. bindings.push( instanceGroup );
  31531. }
  31532. }
  31533. return bindings;
  31534. }
  31535. }
  31536. /**
  31537. * {@link NodeBuilder} is going to create instances of this class during the build process
  31538. * of nodes. They represent the final shader attributes that are going to be generated
  31539. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  31540. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  31541. */
  31542. class NodeAttribute {
  31543. /**
  31544. * Constructs a new node attribute.
  31545. *
  31546. * @param {string} name - The name of the attribute.
  31547. * @param {string} type - The type of the attribute.
  31548. * @param {?Node} node - An optional reference to the node.
  31549. */
  31550. constructor( name, type, node = null ) {
  31551. /**
  31552. * This flag can be used for type testing.
  31553. *
  31554. * @type {boolean}
  31555. * @readonly
  31556. * @default true
  31557. */
  31558. this.isNodeAttribute = true;
  31559. /**
  31560. * The name of the attribute.
  31561. *
  31562. * @type {string}
  31563. */
  31564. this.name = name;
  31565. /**
  31566. * The type of the attribute.
  31567. *
  31568. * @type {string}
  31569. */
  31570. this.type = type;
  31571. /**
  31572. * An optional reference to the node.
  31573. *
  31574. * @type {?Node}
  31575. * @default null
  31576. */
  31577. this.node = node;
  31578. }
  31579. }
  31580. /**
  31581. * {@link NodeBuilder} is going to create instances of this class during the build process
  31582. * of nodes. They represent the final shader uniforms that are going to be generated
  31583. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  31584. * for this purpose.
  31585. */
  31586. class NodeUniform {
  31587. /**
  31588. * Constructs a new node uniform.
  31589. *
  31590. * @param {string} name - The name of the uniform.
  31591. * @param {string} type - The type of the uniform.
  31592. * @param {UniformNode} node - An reference to the node.
  31593. */
  31594. constructor( name, type, node ) {
  31595. /**
  31596. * This flag can be used for type testing.
  31597. *
  31598. * @type {boolean}
  31599. * @readonly
  31600. * @default true
  31601. */
  31602. this.isNodeUniform = true;
  31603. /**
  31604. * The name of the uniform.
  31605. *
  31606. * @type {string}
  31607. */
  31608. this.name = name;
  31609. /**
  31610. * The type of the uniform.
  31611. *
  31612. * @type {string}
  31613. */
  31614. this.type = type;
  31615. /**
  31616. * An reference to the node.
  31617. *
  31618. * @type {UniformNode}
  31619. */
  31620. this.node = node.getSelf();
  31621. }
  31622. /**
  31623. * The value of the uniform node.
  31624. *
  31625. * @type {any}
  31626. */
  31627. get value() {
  31628. return this.node.value;
  31629. }
  31630. set value( val ) {
  31631. this.node.value = val;
  31632. }
  31633. /**
  31634. * The id of the uniform node.
  31635. *
  31636. * @type {number}
  31637. */
  31638. get id() {
  31639. return this.node.id;
  31640. }
  31641. /**
  31642. * The uniform node's group.
  31643. *
  31644. * @type {UniformGroupNode}
  31645. */
  31646. get groupNode() {
  31647. return this.node.groupNode;
  31648. }
  31649. }
  31650. /**
  31651. * {@link NodeBuilder} is going to create instances of this class during the build process
  31652. * of nodes. They represent the final shader variables that are going to be generated
  31653. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  31654. * this purpose.
  31655. */
  31656. class NodeVar {
  31657. /**
  31658. * Constructs a new node variable.
  31659. *
  31660. * @param {string} name - The name of the variable.
  31661. * @param {string} type - The type of the variable.
  31662. * @param {boolean} [readOnly=false] - The read-only flag.
  31663. * @param {?number} [count=null] - The size.
  31664. */
  31665. constructor( name, type, readOnly = false, count = null ) {
  31666. /**
  31667. * This flag can be used for type testing.
  31668. *
  31669. * @type {boolean}
  31670. * @readonly
  31671. * @default true
  31672. */
  31673. this.isNodeVar = true;
  31674. /**
  31675. * The name of the variable.
  31676. *
  31677. * @type {string}
  31678. */
  31679. this.name = name;
  31680. /**
  31681. * The type of the variable.
  31682. *
  31683. * @type {string}
  31684. */
  31685. this.type = type;
  31686. /**
  31687. * The read-only flag.
  31688. *
  31689. * @type {boolean}
  31690. */
  31691. this.readOnly = readOnly;
  31692. /**
  31693. * The size.
  31694. *
  31695. * @type {?number}
  31696. */
  31697. this.count = count;
  31698. }
  31699. }
  31700. /**
  31701. * {@link NodeBuilder} is going to create instances of this class during the build process
  31702. * of nodes. They represent the final shader varyings that are going to be generated
  31703. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  31704. * this purpose.
  31705. *
  31706. * @augments NodeVar
  31707. */
  31708. class NodeVarying extends NodeVar {
  31709. /**
  31710. * Constructs a new node varying.
  31711. *
  31712. * @param {string} name - The name of the varying.
  31713. * @param {string} type - The type of the varying.
  31714. * @param {?string} interpolationType - The interpolation type of the varying.
  31715. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  31716. */
  31717. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  31718. super( name, type );
  31719. /**
  31720. * Whether this varying requires interpolation or not. This property can be used
  31721. * to check if the varying can be optimized for a variable.
  31722. *
  31723. * @type {boolean}
  31724. * @default false
  31725. */
  31726. this.needsInterpolation = false;
  31727. /**
  31728. * This flag can be used for type testing.
  31729. *
  31730. * @type {boolean}
  31731. * @readonly
  31732. * @default true
  31733. */
  31734. this.isNodeVarying = true;
  31735. /**
  31736. * The interpolation type of the varying data.
  31737. *
  31738. * @type {?string}
  31739. * @default null
  31740. */
  31741. this.interpolationType = interpolationType;
  31742. /**
  31743. * The interpolation sampling type of varying data.
  31744. *
  31745. * @type {?string}
  31746. * @default null
  31747. */
  31748. this.interpolationSampling = interpolationSampling;
  31749. }
  31750. }
  31751. /**
  31752. * {@link NodeBuilder} is going to create instances of this class during the build process
  31753. * of nodes. They represent user-defined, native shader code portions that are going to be
  31754. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  31755. * for this purpose.
  31756. */
  31757. class NodeCode {
  31758. /**
  31759. * Constructs a new code node.
  31760. *
  31761. * @param {string} name - The name of the code.
  31762. * @param {string} type - The node type.
  31763. * @param {string} [code=''] - The native shader code.
  31764. */
  31765. constructor( name, type, code = '' ) {
  31766. /**
  31767. * The name of the code.
  31768. *
  31769. * @type {string}
  31770. */
  31771. this.name = name;
  31772. /**
  31773. * The node type.
  31774. *
  31775. * @type {string}
  31776. */
  31777. this.type = type;
  31778. /**
  31779. * The native shader code.
  31780. *
  31781. * @type {string}
  31782. * @default ''
  31783. */
  31784. this.code = code;
  31785. Object.defineProperty( this, 'isNodeCode', { value: true } );
  31786. }
  31787. }
  31788. let _id$5 = 0;
  31789. /**
  31790. * This utility class is used in {@link NodeBuilder} as an internal
  31791. * cache data structure for node data.
  31792. */
  31793. class NodeCache {
  31794. /**
  31795. * Constructs a new node cache.
  31796. *
  31797. * @param {?NodeCache} parent - A reference to a parent cache.
  31798. */
  31799. constructor( parent = null ) {
  31800. /**
  31801. * The id of the cache.
  31802. *
  31803. * @type {number}
  31804. * @readonly
  31805. */
  31806. this.id = _id$5 ++;
  31807. /**
  31808. * A weak map for managing node data.
  31809. *
  31810. * @type {WeakMap<Node, Object>}
  31811. */
  31812. this.nodesData = new WeakMap();
  31813. /**
  31814. * Reference to a parent node cache.
  31815. *
  31816. * @type {?NodeCache}
  31817. * @default null
  31818. */
  31819. this.parent = parent;
  31820. }
  31821. /**
  31822. * Returns the data for the given node.
  31823. *
  31824. * @param {Node} node - The node.
  31825. * @return {?Object} The data for the node.
  31826. */
  31827. getData( node ) {
  31828. let data = this.nodesData.get( node );
  31829. if ( data === undefined && this.parent !== null ) {
  31830. data = this.parent.getData( node );
  31831. }
  31832. return data;
  31833. }
  31834. /**
  31835. * Sets the data for a given node.
  31836. *
  31837. * @param {Node} node - The node.
  31838. * @param {Object} data - The data that should be cached.
  31839. */
  31840. setData( node, data ) {
  31841. this.nodesData.set( node, data );
  31842. }
  31843. }
  31844. class StructType {
  31845. constructor( name, members ) {
  31846. this.name = name;
  31847. this.members = members;
  31848. this.output = false;
  31849. }
  31850. }
  31851. /**
  31852. * Abstract base class for uniforms.
  31853. *
  31854. * @abstract
  31855. * @private
  31856. */
  31857. class Uniform {
  31858. /**
  31859. * Constructs a new uniform.
  31860. *
  31861. * @param {string} name - The uniform's name.
  31862. * @param {any} value - The uniform's value.
  31863. */
  31864. constructor( name, value ) {
  31865. /**
  31866. * The uniform's name.
  31867. *
  31868. * @type {string}
  31869. */
  31870. this.name = name;
  31871. /**
  31872. * The uniform's value.
  31873. *
  31874. * @type {any}
  31875. */
  31876. this.value = value;
  31877. /**
  31878. * Used to build the uniform buffer according to the STD140 layout.
  31879. * Derived uniforms will set this property to a data type specific
  31880. * value.
  31881. *
  31882. * @type {number}
  31883. */
  31884. this.boundary = 0;
  31885. /**
  31886. * The item size. Derived uniforms will set this property to a data
  31887. * type specific value.
  31888. *
  31889. * @type {number}
  31890. */
  31891. this.itemSize = 0;
  31892. /**
  31893. * This property is set by {@link UniformsGroup} and marks
  31894. * the start position in the uniform buffer.
  31895. *
  31896. * @type {number}
  31897. */
  31898. this.offset = 0;
  31899. }
  31900. /**
  31901. * Sets the uniform's value.
  31902. *
  31903. * @param {any} value - The value to set.
  31904. */
  31905. setValue( value ) {
  31906. this.value = value;
  31907. }
  31908. /**
  31909. * Returns the uniform's value.
  31910. *
  31911. * @return {any} The value.
  31912. */
  31913. getValue() {
  31914. return this.value;
  31915. }
  31916. }
  31917. /**
  31918. * Represents a Number uniform.
  31919. *
  31920. * @private
  31921. * @augments Uniform
  31922. */
  31923. class NumberUniform extends Uniform {
  31924. /**
  31925. * Constructs a new Number uniform.
  31926. *
  31927. * @param {string} name - The uniform's name.
  31928. * @param {number} value - The uniform's value.
  31929. */
  31930. constructor( name, value = 0 ) {
  31931. super( name, value );
  31932. /**
  31933. * This flag can be used for type testing.
  31934. *
  31935. * @type {boolean}
  31936. * @readonly
  31937. * @default true
  31938. */
  31939. this.isNumberUniform = true;
  31940. this.boundary = 4;
  31941. this.itemSize = 1;
  31942. }
  31943. }
  31944. /**
  31945. * Represents a Vector2 uniform.
  31946. *
  31947. * @private
  31948. * @augments Uniform
  31949. */
  31950. class Vector2Uniform extends Uniform {
  31951. /**
  31952. * Constructs a new Number uniform.
  31953. *
  31954. * @param {string} name - The uniform's name.
  31955. * @param {Vector2} value - The uniform's value.
  31956. */
  31957. constructor( name, value = new Vector2() ) {
  31958. super( name, value );
  31959. /**
  31960. * This flag can be used for type testing.
  31961. *
  31962. * @type {boolean}
  31963. * @readonly
  31964. * @default true
  31965. */
  31966. this.isVector2Uniform = true;
  31967. this.boundary = 8;
  31968. this.itemSize = 2;
  31969. }
  31970. }
  31971. /**
  31972. * Represents a Vector3 uniform.
  31973. *
  31974. * @private
  31975. * @augments Uniform
  31976. */
  31977. class Vector3Uniform extends Uniform {
  31978. /**
  31979. * Constructs a new Number uniform.
  31980. *
  31981. * @param {string} name - The uniform's name.
  31982. * @param {Vector3} value - The uniform's value.
  31983. */
  31984. constructor( name, value = new Vector3() ) {
  31985. super( name, value );
  31986. /**
  31987. * This flag can be used for type testing.
  31988. *
  31989. * @type {boolean}
  31990. * @readonly
  31991. * @default true
  31992. */
  31993. this.isVector3Uniform = true;
  31994. this.boundary = 16;
  31995. this.itemSize = 3;
  31996. }
  31997. }
  31998. /**
  31999. * Represents a Vector4 uniform.
  32000. *
  32001. * @private
  32002. * @augments Uniform
  32003. */
  32004. class Vector4Uniform extends Uniform {
  32005. /**
  32006. * Constructs a new Number uniform.
  32007. *
  32008. * @param {string} name - The uniform's name.
  32009. * @param {Vector4} value - The uniform's value.
  32010. */
  32011. constructor( name, value = new Vector4() ) {
  32012. super( name, value );
  32013. /**
  32014. * This flag can be used for type testing.
  32015. *
  32016. * @type {boolean}
  32017. * @readonly
  32018. * @default true
  32019. */
  32020. this.isVector4Uniform = true;
  32021. this.boundary = 16;
  32022. this.itemSize = 4;
  32023. }
  32024. }
  32025. /**
  32026. * Represents a Color uniform.
  32027. *
  32028. * @private
  32029. * @augments Uniform
  32030. */
  32031. class ColorUniform extends Uniform {
  32032. /**
  32033. * Constructs a new Number uniform.
  32034. *
  32035. * @param {string} name - The uniform's name.
  32036. * @param {Color} value - The uniform's value.
  32037. */
  32038. constructor( name, value = new Color() ) {
  32039. super( name, value );
  32040. /**
  32041. * This flag can be used for type testing.
  32042. *
  32043. * @type {boolean}
  32044. * @readonly
  32045. * @default true
  32046. */
  32047. this.isColorUniform = true;
  32048. this.boundary = 16;
  32049. this.itemSize = 3;
  32050. }
  32051. }
  32052. /**
  32053. * Represents a Matrix2 uniform.
  32054. *
  32055. * @private
  32056. * @augments Uniform
  32057. */
  32058. class Matrix2Uniform extends Uniform {
  32059. /**
  32060. * Constructs a new Number uniform.
  32061. *
  32062. * @param {string} name - The uniform's name.
  32063. * @param {Matrix2} value - The uniform's value.
  32064. */
  32065. constructor( name, value = new Matrix2() ) {
  32066. super( name, value );
  32067. /**
  32068. * This flag can be used for type testing.
  32069. *
  32070. * @type {boolean}
  32071. * @readonly
  32072. * @default true
  32073. */
  32074. this.isMatrix2Uniform = true;
  32075. this.boundary = 8;
  32076. this.itemSize = 4;
  32077. }
  32078. }
  32079. /**
  32080. * Represents a Matrix3 uniform.
  32081. *
  32082. * @private
  32083. * @augments Uniform
  32084. */
  32085. class Matrix3Uniform extends Uniform {
  32086. /**
  32087. * Constructs a new Number uniform.
  32088. *
  32089. * @param {string} name - The uniform's name.
  32090. * @param {Matrix3} value - The uniform's value.
  32091. */
  32092. constructor( name, value = new Matrix3() ) {
  32093. super( name, value );
  32094. /**
  32095. * This flag can be used for type testing.
  32096. *
  32097. * @type {boolean}
  32098. * @readonly
  32099. * @default true
  32100. */
  32101. this.isMatrix3Uniform = true;
  32102. this.boundary = 48;
  32103. this.itemSize = 12;
  32104. }
  32105. }
  32106. /**
  32107. * Represents a Matrix4 uniform.
  32108. *
  32109. * @private
  32110. * @augments Uniform
  32111. */
  32112. class Matrix4Uniform extends Uniform {
  32113. /**
  32114. * Constructs a new Number uniform.
  32115. *
  32116. * @param {string} name - The uniform's name.
  32117. * @param {Matrix4} value - The uniform's value.
  32118. */
  32119. constructor( name, value = new Matrix4() ) {
  32120. super( name, value );
  32121. /**
  32122. * This flag can be used for type testing.
  32123. *
  32124. * @type {boolean}
  32125. * @readonly
  32126. * @default true
  32127. */
  32128. this.isMatrix4Uniform = true;
  32129. this.boundary = 64;
  32130. this.itemSize = 16;
  32131. }
  32132. }
  32133. /**
  32134. * A special form of Number uniform binding type.
  32135. * It's value is managed by a node object.
  32136. *
  32137. * @private
  32138. * @augments NumberUniform
  32139. */
  32140. class NumberNodeUniform extends NumberUniform {
  32141. /**
  32142. * Constructs a new node-based Number uniform.
  32143. *
  32144. * @param {NodeUniform} nodeUniform - The node uniform.
  32145. */
  32146. constructor( nodeUniform ) {
  32147. super( nodeUniform.name, nodeUniform.value );
  32148. /**
  32149. * The node uniform.
  32150. *
  32151. * @type {NodeUniform}
  32152. */
  32153. this.nodeUniform = nodeUniform;
  32154. }
  32155. /**
  32156. * Overwritten to return the value of the node uniform.
  32157. *
  32158. * @return {number} The value.
  32159. */
  32160. getValue() {
  32161. return this.nodeUniform.value;
  32162. }
  32163. /**
  32164. * Returns the node uniform data type.
  32165. *
  32166. * @return {string} The data type.
  32167. */
  32168. getType() {
  32169. return this.nodeUniform.type;
  32170. }
  32171. }
  32172. /**
  32173. * A special form of Vector2 uniform binding type.
  32174. * It's value is managed by a node object.
  32175. *
  32176. * @private
  32177. * @augments Vector2Uniform
  32178. */
  32179. class Vector2NodeUniform extends Vector2Uniform {
  32180. /**
  32181. * Constructs a new node-based Vector2 uniform.
  32182. *
  32183. * @param {NodeUniform} nodeUniform - The node uniform.
  32184. */
  32185. constructor( nodeUniform ) {
  32186. super( nodeUniform.name, nodeUniform.value );
  32187. /**
  32188. * The node uniform.
  32189. *
  32190. * @type {NodeUniform}
  32191. */
  32192. this.nodeUniform = nodeUniform;
  32193. }
  32194. /**
  32195. * Overwritten to return the value of the node uniform.
  32196. *
  32197. * @return {Vector2} The value.
  32198. */
  32199. getValue() {
  32200. return this.nodeUniform.value;
  32201. }
  32202. /**
  32203. * Returns the node uniform data type.
  32204. *
  32205. * @return {string} The data type.
  32206. */
  32207. getType() {
  32208. return this.nodeUniform.type;
  32209. }
  32210. }
  32211. /**
  32212. * A special form of Vector3 uniform binding type.
  32213. * It's value is managed by a node object.
  32214. *
  32215. * @private
  32216. * @augments Vector3Uniform
  32217. */
  32218. class Vector3NodeUniform extends Vector3Uniform {
  32219. /**
  32220. * Constructs a new node-based Vector3 uniform.
  32221. *
  32222. * @param {NodeUniform} nodeUniform - The node uniform.
  32223. */
  32224. constructor( nodeUniform ) {
  32225. super( nodeUniform.name, nodeUniform.value );
  32226. /**
  32227. * The node uniform.
  32228. *
  32229. * @type {NodeUniform}
  32230. */
  32231. this.nodeUniform = nodeUniform;
  32232. }
  32233. /**
  32234. * Overwritten to return the value of the node uniform.
  32235. *
  32236. * @return {Vector3} The value.
  32237. */
  32238. getValue() {
  32239. return this.nodeUniform.value;
  32240. }
  32241. /**
  32242. * Returns the node uniform data type.
  32243. *
  32244. * @return {string} The data type.
  32245. */
  32246. getType() {
  32247. return this.nodeUniform.type;
  32248. }
  32249. }
  32250. /**
  32251. * A special form of Vector4 uniform binding type.
  32252. * It's value is managed by a node object.
  32253. *
  32254. * @private
  32255. * @augments Vector4Uniform
  32256. */
  32257. class Vector4NodeUniform extends Vector4Uniform {
  32258. /**
  32259. * Constructs a new node-based Vector4 uniform.
  32260. *
  32261. * @param {NodeUniform} nodeUniform - The node uniform.
  32262. */
  32263. constructor( nodeUniform ) {
  32264. super( nodeUniform.name, nodeUniform.value );
  32265. /**
  32266. * The node uniform.
  32267. *
  32268. * @type {NodeUniform}
  32269. */
  32270. this.nodeUniform = nodeUniform;
  32271. }
  32272. /**
  32273. * Overwritten to return the value of the node uniform.
  32274. *
  32275. * @return {Vector4} The value.
  32276. */
  32277. getValue() {
  32278. return this.nodeUniform.value;
  32279. }
  32280. /**
  32281. * Returns the node uniform data type.
  32282. *
  32283. * @return {string} The data type.
  32284. */
  32285. getType() {
  32286. return this.nodeUniform.type;
  32287. }
  32288. }
  32289. /**
  32290. * A special form of Color uniform binding type.
  32291. * It's value is managed by a node object.
  32292. *
  32293. * @private
  32294. * @augments ColorUniform
  32295. */
  32296. class ColorNodeUniform extends ColorUniform {
  32297. /**
  32298. * Constructs a new node-based Color uniform.
  32299. *
  32300. * @param {NodeUniform} nodeUniform - The node uniform.
  32301. */
  32302. constructor( nodeUniform ) {
  32303. super( nodeUniform.name, nodeUniform.value );
  32304. /**
  32305. * The node uniform.
  32306. *
  32307. * @type {NodeUniform}
  32308. */
  32309. this.nodeUniform = nodeUniform;
  32310. }
  32311. /**
  32312. * Overwritten to return the value of the node uniform.
  32313. *
  32314. * @return {Color} The value.
  32315. */
  32316. getValue() {
  32317. return this.nodeUniform.value;
  32318. }
  32319. /**
  32320. * Returns the node uniform data type.
  32321. *
  32322. * @return {string} The data type.
  32323. */
  32324. getType() {
  32325. return this.nodeUniform.type;
  32326. }
  32327. }
  32328. /**
  32329. * A special form of Matrix2 uniform binding type.
  32330. * It's value is managed by a node object.
  32331. *
  32332. * @private
  32333. * @augments Matrix2Uniform
  32334. */
  32335. class Matrix2NodeUniform extends Matrix2Uniform {
  32336. /**
  32337. * Constructs a new node-based Matrix2 uniform.
  32338. *
  32339. * @param {NodeUniform} nodeUniform - The node uniform.
  32340. */
  32341. constructor( nodeUniform ) {
  32342. super( nodeUniform.name, nodeUniform.value );
  32343. /**
  32344. * The node uniform.
  32345. *
  32346. * @type {NodeUniform}
  32347. */
  32348. this.nodeUniform = nodeUniform;
  32349. }
  32350. /**
  32351. * Overwritten to return the value of the node uniform.
  32352. *
  32353. * @return {Matrix2} The value.
  32354. */
  32355. getValue() {
  32356. return this.nodeUniform.value;
  32357. }
  32358. /**
  32359. * Returns the node uniform data type.
  32360. *
  32361. * @return {string} The data type.
  32362. */
  32363. getType() {
  32364. return this.nodeUniform.type;
  32365. }
  32366. }
  32367. /**
  32368. * A special form of Matrix3 uniform binding type.
  32369. * It's value is managed by a node object.
  32370. *
  32371. * @private
  32372. * @augments Matrix3Uniform
  32373. */
  32374. class Matrix3NodeUniform extends Matrix3Uniform {
  32375. /**
  32376. * Constructs a new node-based Matrix3 uniform.
  32377. *
  32378. * @param {NodeUniform} nodeUniform - The node uniform.
  32379. */
  32380. constructor( nodeUniform ) {
  32381. super( nodeUniform.name, nodeUniform.value );
  32382. /**
  32383. * The node uniform.
  32384. *
  32385. * @type {NodeUniform}
  32386. */
  32387. this.nodeUniform = nodeUniform;
  32388. }
  32389. /**
  32390. * Overwritten to return the value of the node uniform.
  32391. *
  32392. * @return {Matrix3} The value.
  32393. */
  32394. getValue() {
  32395. return this.nodeUniform.value;
  32396. }
  32397. /**
  32398. * Returns the node uniform data type.
  32399. *
  32400. * @return {string} The data type.
  32401. */
  32402. getType() {
  32403. return this.nodeUniform.type;
  32404. }
  32405. }
  32406. /**
  32407. * A special form of Matrix4 uniform binding type.
  32408. * It's value is managed by a node object.
  32409. *
  32410. * @private
  32411. * @augments Matrix4Uniform
  32412. */
  32413. class Matrix4NodeUniform extends Matrix4Uniform {
  32414. /**
  32415. * Constructs a new node-based Matrix4 uniform.
  32416. *
  32417. * @param {NodeUniform} nodeUniform - The node uniform.
  32418. */
  32419. constructor( nodeUniform ) {
  32420. super( nodeUniform.name, nodeUniform.value );
  32421. /**
  32422. * The node uniform.
  32423. *
  32424. * @type {NodeUniform}
  32425. */
  32426. this.nodeUniform = nodeUniform;
  32427. }
  32428. /**
  32429. * Overwritten to return the value of the node uniform.
  32430. *
  32431. * @return {Matrix4} The value.
  32432. */
  32433. getValue() {
  32434. return this.nodeUniform.value;
  32435. }
  32436. /**
  32437. * Returns the node uniform data type.
  32438. *
  32439. * @return {string} The data type.
  32440. */
  32441. getType() {
  32442. return this.nodeUniform.type;
  32443. }
  32444. }
  32445. const rendererCache = new WeakMap();
  32446. const typeFromArray = new Map( [
  32447. [ Int8Array, 'int' ],
  32448. [ Int16Array, 'int' ],
  32449. [ Int32Array, 'int' ],
  32450. [ Uint8Array, 'uint' ],
  32451. [ Uint16Array, 'uint' ],
  32452. [ Uint32Array, 'uint' ],
  32453. [ Float32Array, 'float' ]
  32454. ] );
  32455. const toFloat = ( value ) => {
  32456. if ( /e/g.test( value ) ) {
  32457. return String( value ).replace( /\+/g, '' );
  32458. } else {
  32459. value = Number( value );
  32460. return value + ( value % 1 ? '' : '.0' );
  32461. }
  32462. };
  32463. /**
  32464. * Base class for builders which generate a shader program based
  32465. * on a 3D object and its node material definition.
  32466. */
  32467. class NodeBuilder {
  32468. /**
  32469. * Constructs a new node builder.
  32470. *
  32471. * @param {Object3D} object - The 3D object.
  32472. * @param {Renderer} renderer - The current renderer.
  32473. * @param {NodeParser} parser - A reference to a node parser.
  32474. */
  32475. constructor( object, renderer, parser ) {
  32476. /**
  32477. * The 3D object.
  32478. *
  32479. * @type {Object3D}
  32480. */
  32481. this.object = object;
  32482. /**
  32483. * The material of the 3D object.
  32484. *
  32485. * @type {?Material}
  32486. */
  32487. this.material = ( object && object.material ) || null;
  32488. /**
  32489. * The geometry of the 3D object.
  32490. *
  32491. * @type {?BufferGeometry}
  32492. */
  32493. this.geometry = ( object && object.geometry ) || null;
  32494. /**
  32495. * The current renderer.
  32496. *
  32497. * @type {Renderer}
  32498. */
  32499. this.renderer = renderer;
  32500. /**
  32501. * A reference to a node parser.
  32502. *
  32503. * @type {NodeParser}
  32504. */
  32505. this.parser = parser;
  32506. /**
  32507. * The scene the 3D object belongs to.
  32508. *
  32509. * @type {?Scene}
  32510. * @default null
  32511. */
  32512. this.scene = null;
  32513. /**
  32514. * The camera the 3D object is rendered with.
  32515. *
  32516. * @type {?Camera}
  32517. * @default null
  32518. */
  32519. this.camera = null;
  32520. /**
  32521. * A list of all nodes the builder is processing
  32522. * for this 3D object.
  32523. *
  32524. * @type {Array<Node>}
  32525. */
  32526. this.nodes = [];
  32527. /**
  32528. * A list of all sequential nodes.
  32529. *
  32530. * @type {Array<Node>}
  32531. */
  32532. this.sequentialNodes = [];
  32533. /**
  32534. * A list of all nodes which {@link Node#update} method should be executed.
  32535. *
  32536. * @type {Array<Node>}
  32537. */
  32538. this.updateNodes = [];
  32539. /**
  32540. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  32541. *
  32542. * @type {Array<Node>}
  32543. */
  32544. this.updateBeforeNodes = [];
  32545. /**
  32546. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  32547. *
  32548. * @type {Array<Node>}
  32549. */
  32550. this.updateAfterNodes = [];
  32551. /**
  32552. * A dictionary that assigns each node to a unique hash.
  32553. *
  32554. * @type {Object<number,Node>}
  32555. */
  32556. this.hashNodes = {};
  32557. /**
  32558. * A reference to a node material observer.
  32559. *
  32560. * @type {?NodeMaterialObserver}
  32561. * @default null
  32562. */
  32563. this.observer = null;
  32564. /**
  32565. * A reference to the current lights node.
  32566. *
  32567. * @type {?LightsNode}
  32568. * @default null
  32569. */
  32570. this.lightsNode = null;
  32571. /**
  32572. * A reference to the current environment node.
  32573. *
  32574. * @type {?Node}
  32575. * @default null
  32576. */
  32577. this.environmentNode = null;
  32578. /**
  32579. * A reference to the current fog node.
  32580. *
  32581. * @type {?Node}
  32582. * @default null
  32583. */
  32584. this.fogNode = null;
  32585. /**
  32586. * The current clipping context.
  32587. *
  32588. * @type {?ClippingContext}
  32589. */
  32590. this.clippingContext = null;
  32591. /**
  32592. * The generated vertex shader.
  32593. *
  32594. * @type {?string}
  32595. */
  32596. this.vertexShader = null;
  32597. /**
  32598. * The generated fragment shader.
  32599. *
  32600. * @type {?string}
  32601. */
  32602. this.fragmentShader = null;
  32603. /**
  32604. * The generated compute shader.
  32605. *
  32606. * @type {?string}
  32607. */
  32608. this.computeShader = null;
  32609. /**
  32610. * Nodes used in the primary flow of code generation.
  32611. *
  32612. * @type {Object<string,Array<Node>>}
  32613. */
  32614. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  32615. /**
  32616. * Nodes code from `.flowNodes`.
  32617. *
  32618. * @type {Object<string,string>}
  32619. */
  32620. this.flowCode = { vertex: '', fragment: '', compute: '' };
  32621. /**
  32622. * This dictionary holds the node uniforms of the builder.
  32623. * The uniforms are maintained in an array for each shader stage.
  32624. *
  32625. * @type {Object}
  32626. */
  32627. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  32628. /**
  32629. * This dictionary holds the output structs of the builder.
  32630. * The structs are maintained in an array for each shader stage.
  32631. *
  32632. * @type {Object}
  32633. */
  32634. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  32635. /**
  32636. * This dictionary holds the bindings for each shader stage.
  32637. *
  32638. * @type {Object}
  32639. */
  32640. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  32641. /**
  32642. * This dictionary maintains the binding indices per bind group.
  32643. *
  32644. * @type {Object}
  32645. */
  32646. this.bindingsIndexes = {};
  32647. /**
  32648. * Reference to the array of bind groups.
  32649. *
  32650. * @type {?Array<BindGroup>}
  32651. */
  32652. this.bindGroups = null;
  32653. /**
  32654. * This array holds the node attributes of this builder
  32655. * created via {@link AttributeNode}.
  32656. *
  32657. * @type {Array<NodeAttribute>}
  32658. */
  32659. this.attributes = [];
  32660. /**
  32661. * This array holds the node attributes of this builder
  32662. * created via {@link BufferAttributeNode}.
  32663. *
  32664. * @type {Array<NodeAttribute>}
  32665. */
  32666. this.bufferAttributes = [];
  32667. /**
  32668. * This array holds the node varyings of this builder.
  32669. *
  32670. * @type {Array<NodeVarying>}
  32671. */
  32672. this.varyings = [];
  32673. /**
  32674. * This dictionary holds the (native) node codes of this builder.
  32675. * The codes are maintained in an array for each shader stage.
  32676. *
  32677. * @type {Object<string,Array<NodeCode>>}
  32678. */
  32679. this.codes = {};
  32680. /**
  32681. * This dictionary holds the node variables of this builder.
  32682. * The variables are maintained in an array for each shader stage.
  32683. * This dictionary is also used to count the number of variables
  32684. * according to their type (const, vars).
  32685. *
  32686. * @type {Object<string,Array<NodeVar>|number>}
  32687. */
  32688. this.vars = {};
  32689. /**
  32690. * This dictionary holds the declarations for each shader stage.
  32691. *
  32692. * @type {Object}
  32693. */
  32694. this.declarations = {};
  32695. /**
  32696. * Current code flow.
  32697. * All code generated in this stack will be stored in `.flow`.
  32698. *
  32699. * @type {{code: string}}
  32700. */
  32701. this.flow = { code: '' };
  32702. /**
  32703. * A chain of nodes.
  32704. * Used to check recursive calls in node-graph.
  32705. *
  32706. * @type {Array<Node>}
  32707. */
  32708. this.chaining = [];
  32709. /**
  32710. * The current stack.
  32711. * This reflects the current process in the code block hierarchy,
  32712. * it is useful to know if the current process is inside a conditional for example.
  32713. *
  32714. * @type {StackNode}
  32715. */
  32716. this.stack = stack();
  32717. /**
  32718. * List of stack nodes.
  32719. * The current stack hierarchy is stored in an array.
  32720. *
  32721. * @type {Array<StackNode>}
  32722. */
  32723. this.stacks = [];
  32724. /**
  32725. * A tab value. Used for shader string generation.
  32726. *
  32727. * @type {string}
  32728. * @default '\t'
  32729. */
  32730. this.tab = '\t';
  32731. /**
  32732. * Reference to the current function node.
  32733. *
  32734. * @type {?FunctionNode}
  32735. * @default null
  32736. */
  32737. this.currentFunctionNode = null;
  32738. /**
  32739. * The builder's context.
  32740. *
  32741. * @type {Object}
  32742. */
  32743. this.context = {
  32744. material: this.material
  32745. };
  32746. /**
  32747. * The builder's cache.
  32748. *
  32749. * @type {NodeCache}
  32750. */
  32751. this.cache = new NodeCache();
  32752. /**
  32753. * Since the {@link NodeBuilder#cache} might be temporarily
  32754. * overwritten by other caches, this member retains the reference
  32755. * to the builder's own cache.
  32756. *
  32757. * @type {NodeCache}
  32758. * @default this.cache
  32759. */
  32760. this.globalCache = this.cache;
  32761. this.flowsData = new WeakMap();
  32762. /**
  32763. * The current shader stage.
  32764. *
  32765. * @type {?('vertex'|'fragment'|'compute'|'any')}
  32766. */
  32767. this.shaderStage = null;
  32768. /**
  32769. * The current build stage.
  32770. *
  32771. * @type {?('setup'|'analyze'|'generate')}
  32772. */
  32773. this.buildStage = null;
  32774. /**
  32775. * The sub-build layers.
  32776. *
  32777. * @type {Array<SubBuildNode>}
  32778. * @default []
  32779. */
  32780. this.subBuildLayers = [];
  32781. /**
  32782. * The current stack of nodes.
  32783. *
  32784. * @type {?StackNode}
  32785. * @default null
  32786. */
  32787. this.currentStack = null;
  32788. /**
  32789. * The current sub-build TSL function(Fn).
  32790. *
  32791. * @type {?string}
  32792. * @default null
  32793. */
  32794. this.subBuildFn = null;
  32795. }
  32796. /**
  32797. * Returns the bind groups of the current renderer.
  32798. *
  32799. * @return {ChainMap} The cache.
  32800. */
  32801. getBindGroupsCache() {
  32802. let bindGroupsCache = rendererCache.get( this.renderer );
  32803. if ( bindGroupsCache === undefined ) {
  32804. bindGroupsCache = new ChainMap();
  32805. rendererCache.set( this.renderer, bindGroupsCache );
  32806. }
  32807. return bindGroupsCache;
  32808. }
  32809. /**
  32810. * Factory method for creating an instance of {@link RenderTarget} with the given
  32811. * dimensions and options.
  32812. *
  32813. * @param {number} width - The width of the render target.
  32814. * @param {number} height - The height of the render target.
  32815. * @param {Object} options - The options of the render target.
  32816. * @return {RenderTarget} The render target.
  32817. */
  32818. createRenderTarget( width, height, options ) {
  32819. return new RenderTarget( width, height, options );
  32820. }
  32821. /**
  32822. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  32823. * dimensions and options.
  32824. *
  32825. * @param {number} size - The size of the cube render target.
  32826. * @param {Object} options - The options of the cube render target.
  32827. * @return {CubeRenderTarget} The cube render target.
  32828. */
  32829. createCubeRenderTarget( size, options ) {
  32830. return new CubeRenderTarget( size, options );
  32831. }
  32832. /**
  32833. * Whether the given node is included in the internal array of nodes or not.
  32834. *
  32835. * @param {Node} node - The node to test.
  32836. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  32837. */
  32838. includes( node ) {
  32839. return this.nodes.includes( node );
  32840. }
  32841. /**
  32842. * Returns the output struct name which is required by
  32843. * {@link OutputStructNode}.
  32844. *
  32845. * @abstract
  32846. * @return {string} The name of the output struct.
  32847. */
  32848. getOutputStructName() {}
  32849. /**
  32850. * Returns a bind group for the given group name and binding.
  32851. *
  32852. * @private
  32853. * @param {string} groupName - The group name.
  32854. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  32855. * @return {BindGroup} The bind group
  32856. */
  32857. _getBindGroup( groupName, bindings ) {
  32858. const bindGroupsCache = this.getBindGroupsCache();
  32859. //
  32860. const bindingsArray = [];
  32861. let sharedGroup = true;
  32862. for ( const binding of bindings ) {
  32863. bindingsArray.push( binding );
  32864. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  32865. }
  32866. //
  32867. let bindGroup;
  32868. if ( sharedGroup ) {
  32869. bindGroup = bindGroupsCache.get( bindingsArray );
  32870. if ( bindGroup === undefined ) {
  32871. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  32872. bindGroupsCache.set( bindingsArray, bindGroup );
  32873. }
  32874. } else {
  32875. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  32876. }
  32877. return bindGroup;
  32878. }
  32879. /**
  32880. * Returns an array of node uniform groups for the given group name and shader stage.
  32881. *
  32882. * @param {string} groupName - The group name.
  32883. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32884. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  32885. */
  32886. getBindGroupArray( groupName, shaderStage ) {
  32887. const bindings = this.bindings[ shaderStage ];
  32888. let bindGroup = bindings[ groupName ];
  32889. if ( bindGroup === undefined ) {
  32890. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  32891. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  32892. }
  32893. bindings[ groupName ] = bindGroup = [];
  32894. }
  32895. return bindGroup;
  32896. }
  32897. /**
  32898. * Returns a list bindings of all shader stages separated by groups.
  32899. *
  32900. * @return {Array<BindGroup>} The list of bindings.
  32901. */
  32902. getBindings() {
  32903. let bindingsGroups = this.bindGroups;
  32904. if ( bindingsGroups === null ) {
  32905. const groups = {};
  32906. const bindings = this.bindings;
  32907. for ( const shaderStage of shaderStages ) {
  32908. for ( const groupName in bindings[ shaderStage ] ) {
  32909. const uniforms = bindings[ shaderStage ][ groupName ];
  32910. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  32911. groupUniforms.push( ...uniforms );
  32912. }
  32913. }
  32914. bindingsGroups = [];
  32915. for ( const groupName in groups ) {
  32916. const group = groups[ groupName ];
  32917. const bindingsGroup = this._getBindGroup( groupName, group );
  32918. bindingsGroups.push( bindingsGroup );
  32919. }
  32920. this.bindGroups = bindingsGroups;
  32921. }
  32922. return bindingsGroups;
  32923. }
  32924. /**
  32925. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  32926. */
  32927. sortBindingGroups() {
  32928. const bindingsGroups = this.getBindings();
  32929. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  32930. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  32931. const bindingGroup = bindingsGroups[ i ];
  32932. this.bindingsIndexes[ bindingGroup.name ].group = i;
  32933. bindingGroup.index = i;
  32934. }
  32935. }
  32936. /**
  32937. * The builder maintains each node in a hash-based dictionary.
  32938. * This method sets the given node (value) with the given hash (key) into this dictionary.
  32939. *
  32940. * @param {Node} node - The node to add.
  32941. * @param {number} hash - The hash of the node.
  32942. */
  32943. setHashNode( node, hash ) {
  32944. this.hashNodes[ hash ] = node;
  32945. }
  32946. /**
  32947. * Adds a node to this builder.
  32948. *
  32949. * @param {Node} node - The node to add.
  32950. */
  32951. addNode( node ) {
  32952. if ( this.nodes.includes( node ) === false ) {
  32953. this.nodes.push( node );
  32954. this.setHashNode( node, node.getHash( this ) );
  32955. }
  32956. }
  32957. /**
  32958. * It is used to add Nodes that will be used as FRAME and RENDER events,
  32959. * and need to follow a certain sequence in the calls to work correctly.
  32960. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  32961. *
  32962. * @param {Node} node - The node to add.
  32963. */
  32964. addSequentialNode( node ) {
  32965. if ( this.sequentialNodes.includes( node ) === false ) {
  32966. this.sequentialNodes.push( node );
  32967. }
  32968. }
  32969. /**
  32970. * Checks the update types of nodes
  32971. */
  32972. buildUpdateNodes() {
  32973. for ( const node of this.nodes ) {
  32974. const updateType = node.getUpdateType();
  32975. if ( updateType !== NodeUpdateType.NONE ) {
  32976. this.updateNodes.push( node.getSelf() );
  32977. }
  32978. }
  32979. for ( const node of this.sequentialNodes ) {
  32980. const updateBeforeType = node.getUpdateBeforeType();
  32981. const updateAfterType = node.getUpdateAfterType();
  32982. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  32983. this.updateBeforeNodes.push( node.getSelf() );
  32984. }
  32985. if ( updateAfterType !== NodeUpdateType.NONE ) {
  32986. this.updateAfterNodes.push( node.getSelf() );
  32987. }
  32988. }
  32989. }
  32990. /**
  32991. * A reference the current node which is the
  32992. * last node in the chain of nodes.
  32993. *
  32994. * @type {Node}
  32995. */
  32996. get currentNode() {
  32997. return this.chaining[ this.chaining.length - 1 ];
  32998. }
  32999. /**
  33000. * Whether the given texture is filtered or not.
  33001. *
  33002. * @param {Texture} texture - The texture to check.
  33003. * @return {boolean} Whether the given texture is filtered or not.
  33004. */
  33005. isFilteredTexture( texture ) {
  33006. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  33007. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  33008. }
  33009. /**
  33010. * Adds the given node to the internal node chain.
  33011. * This is used to check recursive calls in node-graph.
  33012. *
  33013. * @param {Node} node - The node to add.
  33014. */
  33015. addChain( node ) {
  33016. /*
  33017. if ( this.chaining.indexOf( node ) !== - 1 ) {
  33018. console.warn( 'Recursive node: ', node );
  33019. }
  33020. */
  33021. this.chaining.push( node );
  33022. }
  33023. /**
  33024. * Removes the given node from the internal node chain.
  33025. *
  33026. * @param {Node} node - The node to remove.
  33027. */
  33028. removeChain( node ) {
  33029. const lastChain = this.chaining.pop();
  33030. if ( lastChain !== node ) {
  33031. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  33032. }
  33033. }
  33034. /**
  33035. * Returns the native shader method name for a given generic name. E.g.
  33036. * the method name `textureDimensions` matches the WGSL name but must be
  33037. * resolved to `textureSize` in GLSL.
  33038. *
  33039. * @abstract
  33040. * @param {string} method - The method name to resolve.
  33041. * @return {string} The resolved method name.
  33042. */
  33043. getMethod( method ) {
  33044. return method;
  33045. }
  33046. /**
  33047. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  33048. *
  33049. * @param {number} hash - The hash of the node.
  33050. * @return {Node} The found node.
  33051. */
  33052. getNodeFromHash( hash ) {
  33053. return this.hashNodes[ hash ];
  33054. }
  33055. /**
  33056. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  33057. *
  33058. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  33059. * @param {Node} node - The node to add.
  33060. * @return {Node} The node.
  33061. */
  33062. addFlow( shaderStage, node ) {
  33063. this.flowNodes[ shaderStage ].push( node );
  33064. return node;
  33065. }
  33066. /**
  33067. * Sets builder's context.
  33068. *
  33069. * @param {Object} context - The context to set.
  33070. */
  33071. setContext( context ) {
  33072. this.context = context;
  33073. }
  33074. /**
  33075. * Returns the builder's current context.
  33076. *
  33077. * @return {Object} The builder's current context.
  33078. */
  33079. getContext() {
  33080. return this.context;
  33081. }
  33082. /**
  33083. * Gets a context used in shader construction that can be shared across different materials.
  33084. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  33085. *
  33086. * @return {Object} The builder's current context without material.
  33087. */
  33088. getSharedContext() {
  33089. ({ ...this.context });
  33090. return this.context;
  33091. }
  33092. /**
  33093. * Sets builder's cache.
  33094. *
  33095. * @param {NodeCache} cache - The cache to set.
  33096. */
  33097. setCache( cache ) {
  33098. this.cache = cache;
  33099. }
  33100. /**
  33101. * Returns the builder's current cache.
  33102. *
  33103. * @return {NodeCache} The builder's current cache.
  33104. */
  33105. getCache() {
  33106. return this.cache;
  33107. }
  33108. /**
  33109. * Returns a cache for the given node.
  33110. *
  33111. * @param {Node} node - The node.
  33112. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  33113. * @return {NodeCache} The cache.
  33114. */
  33115. getCacheFromNode( node, parent = true ) {
  33116. const data = this.getDataFromNode( node );
  33117. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  33118. return data.cache;
  33119. }
  33120. /**
  33121. * Whether the requested feature is available or not.
  33122. *
  33123. * @abstract
  33124. * @param {string} name - The requested feature.
  33125. * @return {boolean} Whether the requested feature is supported or not.
  33126. */
  33127. isAvailable( /*name*/ ) {
  33128. return false;
  33129. }
  33130. /**
  33131. * Returns the vertexIndex input variable as a native shader string.
  33132. *
  33133. * @abstract
  33134. * @return {string} The instanceIndex shader string.
  33135. */
  33136. getVertexIndex() {
  33137. console.warn( 'Abstract function.' );
  33138. }
  33139. /**
  33140. * Returns the instanceIndex input variable as a native shader string.
  33141. *
  33142. * @abstract
  33143. * @return {string} The instanceIndex shader string.
  33144. */
  33145. getInstanceIndex() {
  33146. console.warn( 'Abstract function.' );
  33147. }
  33148. /**
  33149. * Returns the drawIndex input variable as a native shader string.
  33150. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  33151. *
  33152. * @abstract
  33153. * @return {?string} The drawIndex shader string.
  33154. */
  33155. getDrawIndex() {
  33156. console.warn( 'Abstract function.' );
  33157. }
  33158. /**
  33159. * Returns the frontFacing input variable as a native shader string.
  33160. *
  33161. * @abstract
  33162. * @return {string} The frontFacing shader string.
  33163. */
  33164. getFrontFacing() {
  33165. console.warn( 'Abstract function.' );
  33166. }
  33167. /**
  33168. * Returns the fragCoord input variable as a native shader string.
  33169. *
  33170. * @abstract
  33171. * @return {string} The fragCoord shader string.
  33172. */
  33173. getFragCoord() {
  33174. console.warn( 'Abstract function.' );
  33175. }
  33176. /**
  33177. * Whether to flip texture data along its vertical axis or not. WebGL needs
  33178. * this method evaluate to `true`, WebGPU to `false`.
  33179. *
  33180. * @abstract
  33181. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  33182. */
  33183. isFlipY() {
  33184. return false;
  33185. }
  33186. /**
  33187. * Calling this method increases the usage count for the given node by one.
  33188. *
  33189. * @param {Node} node - The node to increase the usage count for.
  33190. * @return {number} The updated usage count.
  33191. */
  33192. increaseUsage( node ) {
  33193. const nodeData = this.getDataFromNode( node );
  33194. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  33195. return nodeData.usageCount;
  33196. }
  33197. /**
  33198. * Generates a texture sample shader string for the given texture data.
  33199. *
  33200. * @abstract
  33201. * @param {Texture} texture - The texture.
  33202. * @param {string} textureProperty - The texture property name.
  33203. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  33204. * @return {string} The generated shader string.
  33205. */
  33206. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  33207. console.warn( 'Abstract function.' );
  33208. }
  33209. /**
  33210. * Generates a texture LOD shader string for the given texture data.
  33211. *
  33212. * @abstract
  33213. * @param {Texture} texture - The texture.
  33214. * @param {string} textureProperty - The texture property name.
  33215. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  33216. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  33217. * @param {string} levelSnippet - Snippet defining the mip level.
  33218. * @return {string} The generated shader string.
  33219. */
  33220. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  33221. console.warn( 'Abstract function.' );
  33222. }
  33223. /**
  33224. * Generates the array declaration string.
  33225. *
  33226. * @param {string} type - The type.
  33227. * @param {?number} [count] - The count.
  33228. * @return {string} The generated value as a shader string.
  33229. */
  33230. generateArrayDeclaration( type, count ) {
  33231. return this.getType( type ) + '[ ' + count + ' ]';
  33232. }
  33233. /**
  33234. * Generates the array shader string for the given type and value.
  33235. *
  33236. * @param {string} type - The type.
  33237. * @param {?number} [count] - The count.
  33238. * @param {?Array<Node>} [values=null] - The default values.
  33239. * @return {string} The generated value as a shader string.
  33240. */
  33241. generateArray( type, count, values = null ) {
  33242. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  33243. for ( let i = 0; i < count; i ++ ) {
  33244. const value = values ? values[ i ] : null;
  33245. if ( value !== null ) {
  33246. snippet += value.build( this, type );
  33247. } else {
  33248. snippet += this.generateConst( type );
  33249. }
  33250. if ( i < count - 1 ) snippet += ', ';
  33251. }
  33252. snippet += ' )';
  33253. return snippet;
  33254. }
  33255. /**
  33256. * Generates the struct shader string.
  33257. *
  33258. * @param {string} type - The type.
  33259. * @param {Array<Object>} [membersLayout] - The count.
  33260. * @param {?Array<Node>} [values=null] - The default values.
  33261. * @return {string} The generated value as a shader string.
  33262. */
  33263. generateStruct( type, membersLayout, values = null ) {
  33264. const snippets = [];
  33265. for ( const member of membersLayout ) {
  33266. const { name, type } = member;
  33267. if ( values && values[ name ] && values[ name ].isNode ) {
  33268. snippets.push( values[ name ].build( this, type ) );
  33269. } else {
  33270. snippets.push( this.generateConst( type ) );
  33271. }
  33272. }
  33273. return type + '( ' + snippets.join( ', ' ) + ' )';
  33274. }
  33275. /**
  33276. * Generates the shader string for the given type and value.
  33277. *
  33278. * @param {string} type - The type.
  33279. * @param {?any} [value=null] - The value.
  33280. * @return {string} The generated value as a shader string.
  33281. */
  33282. generateConst( type, value = null ) {
  33283. if ( value === null ) {
  33284. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  33285. else if ( type === 'bool' ) value = false;
  33286. else if ( type === 'color' ) value = new Color();
  33287. else if ( type === 'vec2' ) value = new Vector2();
  33288. else if ( type === 'vec3' ) value = new Vector3();
  33289. else if ( type === 'vec4' ) value = new Vector4();
  33290. }
  33291. if ( type === 'float' ) return toFloat( value );
  33292. if ( type === 'int' ) return `${ Math.round( value ) }`;
  33293. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  33294. if ( type === 'bool' ) return value ? 'true' : 'false';
  33295. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  33296. const typeLength = this.getTypeLength( type );
  33297. const componentType = this.getComponentType( type );
  33298. const generateConst = value => this.generateConst( componentType, value );
  33299. if ( typeLength === 2 ) {
  33300. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  33301. } else if ( typeLength === 3 ) {
  33302. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  33303. } else if ( typeLength === 4 && type !== 'mat2' ) {
  33304. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  33305. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  33306. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  33307. } else if ( typeLength > 4 ) {
  33308. return `${ this.getType( type ) }()`;
  33309. }
  33310. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  33311. }
  33312. /**
  33313. * It might be necessary to convert certain data types to different ones
  33314. * so this method can be used to hide the conversion.
  33315. *
  33316. * @param {string} type - The type.
  33317. * @return {string} The updated type.
  33318. */
  33319. getType( type ) {
  33320. if ( type === 'color' ) return 'vec3';
  33321. return type;
  33322. }
  33323. /**
  33324. * Whether the given attribute name is defined in the geometry or not.
  33325. *
  33326. * @param {string} name - The attribute name.
  33327. * @return {boolean} Whether the given attribute name is defined in the geometry.
  33328. */
  33329. hasGeometryAttribute( name ) {
  33330. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  33331. }
  33332. /**
  33333. * Returns a node attribute for the given name and type.
  33334. *
  33335. * @param {string} name - The attribute's name.
  33336. * @param {string} type - The attribute's type.
  33337. * @return {NodeAttribute} The node attribute.
  33338. */
  33339. getAttribute( name, type ) {
  33340. const attributes = this.attributes;
  33341. // find attribute
  33342. for ( const attribute of attributes ) {
  33343. if ( attribute.name === name ) {
  33344. return attribute;
  33345. }
  33346. }
  33347. // create a new if no exist
  33348. const attribute = new NodeAttribute( name, type );
  33349. this.registerDeclaration( attribute );
  33350. attributes.push( attribute );
  33351. return attribute;
  33352. }
  33353. /**
  33354. * Returns for the given node and shader stage the property name for the shader.
  33355. *
  33356. * @param {Node} node - The node.
  33357. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33358. * @return {string} The property name.
  33359. */
  33360. getPropertyName( node/*, shaderStage*/ ) {
  33361. return node.name;
  33362. }
  33363. /**
  33364. * Whether the given type is a vector type or not.
  33365. *
  33366. * @param {string} type - The type to check.
  33367. * @return {boolean} Whether the given type is a vector type or not.
  33368. */
  33369. isVector( type ) {
  33370. return /vec\d/.test( type );
  33371. }
  33372. /**
  33373. * Whether the given type is a matrix type or not.
  33374. *
  33375. * @param {string} type - The type to check.
  33376. * @return {boolean} Whether the given type is a matrix type or not.
  33377. */
  33378. isMatrix( type ) {
  33379. return /mat\d/.test( type );
  33380. }
  33381. /**
  33382. * Whether the given type is a reference type or not.
  33383. *
  33384. * @param {string} type - The type to check.
  33385. * @return {boolean} Whether the given type is a reference type or not.
  33386. */
  33387. isReference( type ) {
  33388. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  33389. }
  33390. /**
  33391. * Checks if the given texture requires a manual conversion to the working color space.
  33392. *
  33393. * @abstract
  33394. * @param {Texture} texture - The texture to check.
  33395. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  33396. */
  33397. needsToWorkingColorSpace( /*texture*/ ) {
  33398. return false;
  33399. }
  33400. /**
  33401. * Returns the component type of a given texture.
  33402. *
  33403. * @param {Texture} texture - The texture.
  33404. * @return {string} The component type.
  33405. */
  33406. getComponentTypeFromTexture( texture ) {
  33407. const type = texture.type;
  33408. if ( texture.isDataTexture ) {
  33409. if ( type === IntType ) return 'int';
  33410. if ( type === UnsignedIntType ) return 'uint';
  33411. }
  33412. return 'float';
  33413. }
  33414. /**
  33415. * Returns the element type for a given type.
  33416. *
  33417. * @param {string} type - The type.
  33418. * @return {string} The element type.
  33419. */
  33420. getElementType( type ) {
  33421. if ( type === 'mat2' ) return 'vec2';
  33422. if ( type === 'mat3' ) return 'vec3';
  33423. if ( type === 'mat4' ) return 'vec4';
  33424. return this.getComponentType( type );
  33425. }
  33426. /**
  33427. * Returns the component type for a given type.
  33428. *
  33429. * @param {string} type - The type.
  33430. * @return {string} The component type.
  33431. */
  33432. getComponentType( type ) {
  33433. type = this.getVectorType( type );
  33434. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  33435. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  33436. if ( componentType === null ) return null;
  33437. if ( componentType[ 1 ] === 'b' ) return 'bool';
  33438. if ( componentType[ 1 ] === 'i' ) return 'int';
  33439. if ( componentType[ 1 ] === 'u' ) return 'uint';
  33440. return 'float';
  33441. }
  33442. /**
  33443. * Returns the vector type for a given type.
  33444. *
  33445. * @param {string} type - The type.
  33446. * @return {string} The vector type.
  33447. */
  33448. getVectorType( type ) {
  33449. if ( type === 'color' ) return 'vec3';
  33450. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  33451. return type;
  33452. }
  33453. /**
  33454. * Returns the data type for the given the length and component type.
  33455. *
  33456. * @param {number} length - The length.
  33457. * @param {string} [componentType='float'] - The component type.
  33458. * @return {string} The type.
  33459. */
  33460. getTypeFromLength( length, componentType = 'float' ) {
  33461. if ( length === 1 ) return componentType;
  33462. let baseType = getTypeFromLength( length );
  33463. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  33464. // fix edge case for mat2x2 being same size as vec4
  33465. if ( /mat2/.test( componentType ) === true ) {
  33466. baseType = baseType.replace( 'vec', 'mat' );
  33467. }
  33468. return prefix + baseType;
  33469. }
  33470. /**
  33471. * Returns the type for a given typed array.
  33472. *
  33473. * @param {TypedArray} array - The typed array.
  33474. * @return {string} The type.
  33475. */
  33476. getTypeFromArray( array ) {
  33477. return typeFromArray.get( array.constructor );
  33478. }
  33479. /**
  33480. * Returns the type is an integer type.
  33481. *
  33482. * @param {string} type - The type.
  33483. * @return {boolean} Whether the type is an integer type or not.
  33484. */
  33485. isInteger( type ) {
  33486. return /int|uint|(i|u)vec/.test( type );
  33487. }
  33488. /**
  33489. * Returns the type for a given buffer attribute.
  33490. *
  33491. * @param {BufferAttribute} attribute - The buffer attribute.
  33492. * @return {string} The type.
  33493. */
  33494. getTypeFromAttribute( attribute ) {
  33495. let dataAttribute = attribute;
  33496. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  33497. const array = dataAttribute.array;
  33498. const itemSize = attribute.itemSize;
  33499. const normalized = attribute.normalized;
  33500. let arrayType;
  33501. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  33502. arrayType = this.getTypeFromArray( array );
  33503. }
  33504. return this.getTypeFromLength( itemSize, arrayType );
  33505. }
  33506. /**
  33507. * Returns the length for the given data type.
  33508. *
  33509. * @param {string} type - The data type.
  33510. * @return {number} The length.
  33511. */
  33512. getTypeLength( type ) {
  33513. const vecType = this.getVectorType( type );
  33514. const vecNum = /vec([2-4])/.exec( vecType );
  33515. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  33516. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  33517. if ( /mat2/.test( type ) === true ) return 4;
  33518. if ( /mat3/.test( type ) === true ) return 9;
  33519. if ( /mat4/.test( type ) === true ) return 16;
  33520. return 0;
  33521. }
  33522. /**
  33523. * Returns the vector type for a given matrix type.
  33524. *
  33525. * @param {string} type - The matrix type.
  33526. * @return {string} The vector type.
  33527. */
  33528. getVectorFromMatrix( type ) {
  33529. return type.replace( 'mat', 'vec' );
  33530. }
  33531. /**
  33532. * For a given type this method changes the component type to the
  33533. * given value. E.g. `vec4` should be changed to the new component type
  33534. * `uint` which results in `uvec4`.
  33535. *
  33536. * @param {string} type - The type.
  33537. * @param {string} newComponentType - The new component type.
  33538. * @return {string} The new type.
  33539. */
  33540. changeComponentType( type, newComponentType ) {
  33541. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  33542. }
  33543. /**
  33544. * Returns the integer type pendant for the given type.
  33545. *
  33546. * @param {string} type - The type.
  33547. * @return {string} The integer type.
  33548. */
  33549. getIntegerType( type ) {
  33550. const componentType = this.getComponentType( type );
  33551. if ( componentType === 'int' || componentType === 'uint' ) return type;
  33552. return this.changeComponentType( type, 'int' );
  33553. }
  33554. /**
  33555. * Adds a stack node to the internal stack.
  33556. *
  33557. * @return {StackNode} The added stack node.
  33558. */
  33559. addStack() {
  33560. this.stack = stack( this.stack );
  33561. this.stacks.push( getCurrentStack() || this.stack );
  33562. setCurrentStack( this.stack );
  33563. return this.stack;
  33564. }
  33565. /**
  33566. * Removes the last stack node from the internal stack.
  33567. *
  33568. * @return {StackNode} The removed stack node.
  33569. */
  33570. removeStack() {
  33571. const lastStack = this.stack;
  33572. this.stack = lastStack.parent;
  33573. setCurrentStack( this.stacks.pop() );
  33574. return lastStack;
  33575. }
  33576. /**
  33577. * The builder maintains (cached) data for each node during the building process. This method
  33578. * can be used to get these data for a specific shader stage and cache.
  33579. *
  33580. * @param {Node} node - The node to get the data for.
  33581. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33582. * @param {?NodeCache} cache - An optional cache.
  33583. * @return {Object} The node data.
  33584. */
  33585. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  33586. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  33587. let nodeData = cache.getData( node );
  33588. if ( nodeData === undefined ) {
  33589. nodeData = {};
  33590. cache.setData( node, nodeData );
  33591. }
  33592. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  33593. //
  33594. let data = nodeData[ shaderStage ];
  33595. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  33596. const subBuild = this.getClosestSubBuild( subBuilds );
  33597. if ( subBuild ) {
  33598. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  33599. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  33600. data.subBuilds = subBuilds;
  33601. }
  33602. return data;
  33603. }
  33604. /**
  33605. * Returns the properties for the given node and shader stage.
  33606. *
  33607. * @param {Node} node - The node to get the properties for.
  33608. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  33609. * @return {Object} The node properties.
  33610. */
  33611. getNodeProperties( node, shaderStage = 'any' ) {
  33612. const nodeData = this.getDataFromNode( node, shaderStage );
  33613. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  33614. }
  33615. /**
  33616. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  33617. *
  33618. * @param {BufferAttributeNode} node - The buffer attribute node.
  33619. * @param {string} type - The node type.
  33620. * @return {NodeAttribute} The node attribute.
  33621. */
  33622. getBufferAttributeFromNode( node, type ) {
  33623. const nodeData = this.getDataFromNode( node );
  33624. let bufferAttribute = nodeData.bufferAttribute;
  33625. if ( bufferAttribute === undefined ) {
  33626. const index = this.uniforms.index ++;
  33627. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  33628. this.bufferAttributes.push( bufferAttribute );
  33629. nodeData.bufferAttribute = bufferAttribute;
  33630. }
  33631. return bufferAttribute;
  33632. }
  33633. /**
  33634. * Returns an instance of {@link StructType} for the given output struct node.
  33635. *
  33636. * @param {OutputStructNode} node - The output struct node.
  33637. * @param {Array<Object>} membersLayout - The output struct types.
  33638. * @param {?string} [name=null] - The name of the struct.
  33639. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33640. * @return {StructType} The struct type attribute.
  33641. */
  33642. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  33643. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  33644. let structType = nodeData.structType;
  33645. if ( structType === undefined ) {
  33646. const index = this.structs.index ++;
  33647. if ( name === null ) name = 'StructType' + index;
  33648. structType = new StructType( name, membersLayout );
  33649. this.structs[ shaderStage ].push( structType );
  33650. nodeData.structType = structType;
  33651. }
  33652. return structType;
  33653. }
  33654. /**
  33655. * Returns an instance of {@link StructType} for the given output struct node.
  33656. *
  33657. * @param {OutputStructNode} node - The output struct node.
  33658. * @param {Array<Object>} membersLayout - The output struct types.
  33659. * @return {StructType} The struct type attribute.
  33660. */
  33661. getOutputStructTypeFromNode( node, membersLayout ) {
  33662. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  33663. structType.output = true;
  33664. return structType;
  33665. }
  33666. /**
  33667. * Returns an instance of {@link NodeUniform} for the given uniform node.
  33668. *
  33669. * @param {UniformNode} node - The uniform node.
  33670. * @param {string} type - The uniform type.
  33671. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33672. * @param {?string} name - The name of the uniform.
  33673. * @return {NodeUniform} The node uniform.
  33674. */
  33675. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  33676. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  33677. let nodeUniform = nodeData.uniform;
  33678. if ( nodeUniform === undefined ) {
  33679. const index = this.uniforms.index ++;
  33680. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  33681. this.uniforms[ shaderStage ].push( nodeUniform );
  33682. this.registerDeclaration( nodeUniform );
  33683. nodeData.uniform = nodeUniform;
  33684. }
  33685. return nodeUniform;
  33686. }
  33687. /**
  33688. * Returns an instance of {@link NodeVar} for the given variable node.
  33689. *
  33690. * @param {VarNode} node - The variable node.
  33691. * @param {?string} name - The variable's name.
  33692. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  33693. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33694. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  33695. *
  33696. * @return {NodeVar} The node variable.
  33697. */
  33698. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  33699. const nodeData = this.getDataFromNode( node, shaderStage );
  33700. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  33701. let nodeVar = nodeData[ subBuildVariable ];
  33702. if ( nodeVar === undefined ) {
  33703. const idNS = readOnly ? '_const' : '_var';
  33704. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  33705. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  33706. if ( name === null ) {
  33707. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  33708. this.vars[ idNS ] ++;
  33709. }
  33710. //
  33711. if ( subBuildVariable !== 'variable' ) {
  33712. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  33713. }
  33714. //
  33715. const count = node.getArrayCount( this );
  33716. nodeVar = new NodeVar( name, type, readOnly, count );
  33717. if ( ! readOnly ) {
  33718. vars.push( nodeVar );
  33719. }
  33720. this.registerDeclaration( nodeVar );
  33721. nodeData[ subBuildVariable ] = nodeVar;
  33722. }
  33723. return nodeVar;
  33724. }
  33725. /**
  33726. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  33727. *
  33728. * @param {Node} node - The varying node.
  33729. * @return {boolean} Returns true if deterministic.
  33730. */
  33731. isDeterministic( node ) {
  33732. if ( node.isMathNode ) {
  33733. return this.isDeterministic( node.aNode ) &&
  33734. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  33735. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  33736. } else if ( node.isOperatorNode ) {
  33737. return this.isDeterministic( node.aNode ) &&
  33738. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  33739. } else if ( node.isArrayNode ) {
  33740. if ( node.values !== null ) {
  33741. for ( const n of node.values ) {
  33742. if ( ! this.isDeterministic( n ) ) {
  33743. return false;
  33744. }
  33745. }
  33746. }
  33747. return true;
  33748. } else if ( node.isConstNode ) {
  33749. return true;
  33750. }
  33751. return false;
  33752. }
  33753. /**
  33754. * Returns an instance of {@link NodeVarying} for the given varying node.
  33755. *
  33756. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  33757. * @param {?string} name - The varying's name.
  33758. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  33759. * @param {?string} interpolationType - The interpolation type of the varying.
  33760. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  33761. * @return {NodeVar} The node varying.
  33762. */
  33763. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  33764. const nodeData = this.getDataFromNode( node, 'any' );
  33765. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  33766. let nodeVarying = nodeData[ subBuildVarying ];
  33767. if ( nodeVarying === undefined ) {
  33768. const varyings = this.varyings;
  33769. const index = varyings.length;
  33770. if ( name === null ) name = 'nodeVarying' + index;
  33771. //
  33772. if ( subBuildVarying !== 'varying' ) {
  33773. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  33774. }
  33775. //
  33776. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  33777. varyings.push( nodeVarying );
  33778. this.registerDeclaration( nodeVarying );
  33779. nodeData[ subBuildVarying ] = nodeVarying;
  33780. }
  33781. return nodeVarying;
  33782. }
  33783. /**
  33784. * Registers a node declaration in the current shader stage.
  33785. *
  33786. * @param {Object} node - The node to be registered.
  33787. */
  33788. registerDeclaration( node ) {
  33789. const shaderStage = this.shaderStage;
  33790. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  33791. const property = this.getPropertyName( node );
  33792. let index = 1;
  33793. let name = property;
  33794. // Automatically renames the property if the name is already in use.
  33795. while ( declarations[ name ] !== undefined ) {
  33796. name = property + '_' + index ++;
  33797. }
  33798. if ( index > 1 ) {
  33799. node.name = name;
  33800. console.warn( `THREE.TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  33801. }
  33802. declarations[ name ] = node;
  33803. }
  33804. /**
  33805. * Returns an instance of {@link NodeCode} for the given code node.
  33806. *
  33807. * @param {CodeNode} node - The code node.
  33808. * @param {string} type - The node type.
  33809. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33810. * @return {NodeCode} The node code.
  33811. */
  33812. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  33813. const nodeData = this.getDataFromNode( node );
  33814. let nodeCode = nodeData.code;
  33815. if ( nodeCode === undefined ) {
  33816. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  33817. const index = codes.length;
  33818. nodeCode = new NodeCode( 'nodeCode' + index, type );
  33819. codes.push( nodeCode );
  33820. nodeData.code = nodeCode;
  33821. }
  33822. return nodeCode;
  33823. }
  33824. /**
  33825. * Adds a code flow based on the code-block hierarchy.
  33826. * This is used so that code-blocks like If,Else create their variables locally if the Node
  33827. * is only used inside one of these conditionals in the current shader stage.
  33828. *
  33829. * @param {Node} node - The node to add.
  33830. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  33831. */
  33832. addFlowCodeHierarchy( node, nodeBlock ) {
  33833. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  33834. let needsFlowCode = true;
  33835. let nodeBlockHierarchy = nodeBlock;
  33836. while ( nodeBlockHierarchy ) {
  33837. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  33838. needsFlowCode = false;
  33839. break;
  33840. }
  33841. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  33842. }
  33843. if ( needsFlowCode ) {
  33844. for ( const flowCode of flowCodes ) {
  33845. this.addLineFlowCode( flowCode );
  33846. }
  33847. }
  33848. }
  33849. /**
  33850. * Add a inline-code to the current flow code-block.
  33851. *
  33852. * @param {Node} node - The node to add.
  33853. * @param {string} code - The code to add.
  33854. * @param {Node} nodeBlock - Current ConditionalNode
  33855. */
  33856. addLineFlowCodeBlock( node, code, nodeBlock ) {
  33857. const nodeData = this.getDataFromNode( node );
  33858. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  33859. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  33860. flowCodes.push( code );
  33861. codeBlock.set( nodeBlock, true );
  33862. }
  33863. /**
  33864. * Add a inline-code to the current flow.
  33865. *
  33866. * @param {string} code - The code to add.
  33867. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  33868. * @return {NodeBuilder} A reference to this node builder.
  33869. */
  33870. addLineFlowCode( code, node = null ) {
  33871. if ( code === '' ) return this;
  33872. if ( node !== null && this.context.nodeBlock ) {
  33873. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  33874. }
  33875. code = this.tab + code;
  33876. if ( ! /;\s*$/.test( code ) ) {
  33877. code = code + ';\n';
  33878. }
  33879. this.flow.code += code;
  33880. return this;
  33881. }
  33882. /**
  33883. * Adds a code to the current code flow.
  33884. *
  33885. * @param {string} code - Shader code.
  33886. * @return {NodeBuilder} A reference to this node builder.
  33887. */
  33888. addFlowCode( code ) {
  33889. this.flow.code += code;
  33890. return this;
  33891. }
  33892. /**
  33893. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  33894. * Typically used in codes with If,Else.
  33895. *
  33896. * @return {NodeBuilder} A reference to this node builder.
  33897. */
  33898. addFlowTab() {
  33899. this.tab += '\t';
  33900. return this;
  33901. }
  33902. /**
  33903. * Removes a tab.
  33904. *
  33905. * @return {NodeBuilder} A reference to this node builder.
  33906. */
  33907. removeFlowTab() {
  33908. this.tab = this.tab.slice( 0, -1 );
  33909. return this;
  33910. }
  33911. /**
  33912. * Gets the current flow data based on a Node.
  33913. *
  33914. * @param {Node} node - Node that the flow was started.
  33915. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33916. * @return {Object} The flow data.
  33917. */
  33918. getFlowData( node/*, shaderStage*/ ) {
  33919. return this.flowsData.get( node );
  33920. }
  33921. /**
  33922. * Executes the node flow based on a root node to generate the final shader code.
  33923. *
  33924. * @param {Node} node - The node to execute.
  33925. * @return {Object} The code flow.
  33926. */
  33927. flowNode( node ) {
  33928. const output = node.getNodeType( this );
  33929. const flowData = this.flowChildNode( node, output );
  33930. this.flowsData.set( node, flowData );
  33931. return flowData;
  33932. }
  33933. /**
  33934. * Includes a node in the current function node.
  33935. *
  33936. * @param {Node} node - The node to include.
  33937. * @returns {void}
  33938. */
  33939. addInclude( node ) {
  33940. if ( this.currentFunctionNode !== null ) {
  33941. this.currentFunctionNode.includes.push( node );
  33942. }
  33943. }
  33944. /**
  33945. * Returns the native shader operator name for a given generic name.
  33946. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  33947. *
  33948. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  33949. * @return {FunctionNode} The build function node.
  33950. */
  33951. buildFunctionNode( shaderNode ) {
  33952. const fn = new FunctionNode();
  33953. const previous = this.currentFunctionNode;
  33954. this.currentFunctionNode = fn;
  33955. fn.code = this.buildFunctionCode( shaderNode );
  33956. this.currentFunctionNode = previous;
  33957. return fn;
  33958. }
  33959. /**
  33960. * Generates a code flow based on a TSL function: Fn().
  33961. *
  33962. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  33963. * @return {Object}
  33964. */
  33965. flowShaderNode( shaderNode ) {
  33966. const layout = shaderNode.layout;
  33967. const inputs = {
  33968. [ Symbol.iterator ]() {
  33969. let index = 0;
  33970. const values = Object.values( this );
  33971. return {
  33972. next: () => ( {
  33973. value: values[ index ],
  33974. done: index ++ >= values.length
  33975. } )
  33976. };
  33977. }
  33978. };
  33979. for ( const input of layout.inputs ) {
  33980. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  33981. }
  33982. //
  33983. shaderNode.layout = null;
  33984. const callNode = shaderNode.call( inputs );
  33985. const flowData = this.flowStagesNode( callNode, layout.type );
  33986. shaderNode.layout = layout;
  33987. return flowData;
  33988. }
  33989. /**
  33990. * Executes the node in a specific build stage.
  33991. *
  33992. * @param {Node} node - The node to execute.
  33993. * @param {string} buildStage - The build stage to execute the node in.
  33994. * @param {Node|string|null} output - Expected output type. For example 'vec3'.
  33995. * @return {Node|string|null} The result of the node build.
  33996. */
  33997. flowBuildStage( node, buildStage, output = null ) {
  33998. const previousBuildStage = this.getBuildStage();
  33999. this.setBuildStage( buildStage );
  34000. const result = node.build( this, output );
  34001. this.setBuildStage( previousBuildStage );
  34002. return result;
  34003. }
  34004. /**
  34005. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  34006. *
  34007. * @param {Node} node - The node to execute.
  34008. * @param {?string} output - Expected output type. For example 'vec3'.
  34009. * @return {Object}
  34010. */
  34011. flowStagesNode( node, output = null ) {
  34012. const previousFlow = this.flow;
  34013. const previousVars = this.vars;
  34014. const previousDeclarations = this.declarations;
  34015. const previousCache = this.cache;
  34016. const previousBuildStage = this.buildStage;
  34017. const previousStack = this.stack;
  34018. const flow = {
  34019. code: ''
  34020. };
  34021. this.flow = flow;
  34022. this.vars = {};
  34023. this.declarations = {};
  34024. this.cache = new NodeCache();
  34025. this.stack = stack();
  34026. for ( const buildStage of defaultBuildStages ) {
  34027. this.setBuildStage( buildStage );
  34028. flow.result = node.build( this, output );
  34029. }
  34030. flow.vars = this.getVars( this.shaderStage );
  34031. this.flow = previousFlow;
  34032. this.vars = previousVars;
  34033. this.declarations = previousDeclarations;
  34034. this.cache = previousCache;
  34035. this.stack = previousStack;
  34036. this.setBuildStage( previousBuildStage );
  34037. return flow;
  34038. }
  34039. /**
  34040. * Returns the native shader operator name for a given generic name.
  34041. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  34042. *
  34043. * @abstract
  34044. * @param {string} op - The operator name to resolve.
  34045. * @return {?string} The resolved operator name.
  34046. */
  34047. getFunctionOperator( /* op */ ) {
  34048. return null;
  34049. }
  34050. /**
  34051. * Builds the given shader node.
  34052. *
  34053. * @abstract
  34054. * @param {ShaderNodeInternal} shaderNode - The shader node.
  34055. * @return {string} The function code.
  34056. */
  34057. buildFunctionCode( /* shaderNode */ ) {
  34058. console.warn( 'Abstract function.' );
  34059. }
  34060. /**
  34061. * Generates a code flow based on a child Node.
  34062. *
  34063. * @param {Node} node - The node to execute.
  34064. * @param {?string} output - Expected output type. For example 'vec3'.
  34065. * @return {Object} The code flow.
  34066. */
  34067. flowChildNode( node, output = null ) {
  34068. const previousFlow = this.flow;
  34069. const flow = {
  34070. code: ''
  34071. };
  34072. this.flow = flow;
  34073. flow.result = node.build( this, output );
  34074. this.flow = previousFlow;
  34075. return flow;
  34076. }
  34077. /**
  34078. * Executes a flow of code in a different stage.
  34079. *
  34080. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  34081. * return the value in fragment-stage even if it is being executed in an input fragment.
  34082. *
  34083. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34084. * @param {Node} node - The node to execute.
  34085. * @param {?string} output - Expected output type. For example 'vec3'.
  34086. * @param {?string} propertyName - The property name to assign the result.
  34087. * @return {Object|Node|null} The code flow or node.build() result.
  34088. */
  34089. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  34090. const previousTab = this.tab;
  34091. const previousCache = this.cache;
  34092. const previousShaderStage = this.shaderStage;
  34093. const previousContext = this.context;
  34094. this.setShaderStage( shaderStage );
  34095. const context = { ...this.context };
  34096. delete context.nodeBlock;
  34097. this.cache = this.globalCache;
  34098. this.tab = '\t';
  34099. this.context = context;
  34100. let result = null;
  34101. if ( this.buildStage === 'generate' ) {
  34102. const flowData = this.flowChildNode( node, output );
  34103. if ( propertyName !== null ) {
  34104. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  34105. }
  34106. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  34107. result = flowData;
  34108. } else {
  34109. result = node.build( this );
  34110. }
  34111. this.setShaderStage( previousShaderStage );
  34112. this.cache = previousCache;
  34113. this.tab = previousTab;
  34114. this.context = previousContext;
  34115. return result;
  34116. }
  34117. /**
  34118. * Returns an array holding all node attributes of this node builder.
  34119. *
  34120. * @return {Array<NodeAttribute>} The node attributes of this builder.
  34121. */
  34122. getAttributesArray() {
  34123. return this.attributes.concat( this.bufferAttributes );
  34124. }
  34125. /**
  34126. * Returns the attribute definitions as a shader string for the given shader stage.
  34127. *
  34128. * @abstract
  34129. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34130. * @return {string} The attribute code section.
  34131. */
  34132. getAttributes( /*shaderStage*/ ) {
  34133. console.warn( 'Abstract function.' );
  34134. }
  34135. /**
  34136. * Returns the varying definitions as a shader string for the given shader stage.
  34137. *
  34138. * @abstract
  34139. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34140. * @return {string} The varying code section.
  34141. */
  34142. getVaryings( /*shaderStage*/ ) {
  34143. console.warn( 'Abstract function.' );
  34144. }
  34145. /**
  34146. * Returns a single variable definition as a shader string for the given variable type and name.
  34147. *
  34148. * @param {string} type - The variable's type.
  34149. * @param {string} name - The variable's name.
  34150. * @param {?number} [count=null] - The array length.
  34151. * @return {string} The shader string.
  34152. */
  34153. getVar( type, name, count = null ) {
  34154. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  34155. }
  34156. /**
  34157. * Returns the variable definitions as a shader string for the given shader stage.
  34158. *
  34159. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34160. * @return {string} The variable code section.
  34161. */
  34162. getVars( shaderStage ) {
  34163. let snippet = '';
  34164. const vars = this.vars[ shaderStage ];
  34165. if ( vars !== undefined ) {
  34166. for ( const variable of vars ) {
  34167. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  34168. }
  34169. }
  34170. return snippet;
  34171. }
  34172. /**
  34173. * Returns the uniform definitions as a shader string for the given shader stage.
  34174. *
  34175. * @abstract
  34176. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34177. * @return {string} The uniform code section.
  34178. */
  34179. getUniforms( /*shaderStage*/ ) {
  34180. console.warn( 'Abstract function.' );
  34181. }
  34182. /**
  34183. * Returns the native code definitions as a shader string for the given shader stage.
  34184. *
  34185. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34186. * @return {string} The native code section.
  34187. */
  34188. getCodes( shaderStage ) {
  34189. const codes = this.codes[ shaderStage ];
  34190. let code = '';
  34191. if ( codes !== undefined ) {
  34192. for ( const nodeCode of codes ) {
  34193. code += nodeCode.code + '\n';
  34194. }
  34195. }
  34196. return code;
  34197. }
  34198. /**
  34199. * Returns the hash of this node builder.
  34200. *
  34201. * @return {string} The hash.
  34202. */
  34203. getHash() {
  34204. return this.vertexShader + this.fragmentShader + this.computeShader;
  34205. }
  34206. /**
  34207. * Sets the current shader stage.
  34208. *
  34209. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  34210. */
  34211. setShaderStage( shaderStage ) {
  34212. this.shaderStage = shaderStage;
  34213. }
  34214. /**
  34215. * Returns the current shader stage.
  34216. *
  34217. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  34218. */
  34219. getShaderStage() {
  34220. return this.shaderStage;
  34221. }
  34222. /**
  34223. * Sets the current build stage.
  34224. *
  34225. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  34226. */
  34227. setBuildStage( buildStage ) {
  34228. this.buildStage = buildStage;
  34229. }
  34230. /**
  34231. * Returns the current build stage.
  34232. *
  34233. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  34234. */
  34235. getBuildStage() {
  34236. return this.buildStage;
  34237. }
  34238. /**
  34239. * Controls the code build of the shader stages.
  34240. *
  34241. * @abstract
  34242. */
  34243. buildCode() {
  34244. console.warn( 'Abstract function.' );
  34245. }
  34246. /**
  34247. * Returns the current sub-build layer.
  34248. *
  34249. * @return {SubBuildNode} The current sub-build layers.
  34250. */
  34251. get subBuild() {
  34252. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  34253. }
  34254. /**
  34255. * Adds a sub-build layer to the node builder.
  34256. *
  34257. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  34258. */
  34259. addSubBuild( subBuild ) {
  34260. this.subBuildLayers.push( subBuild );
  34261. }
  34262. /**
  34263. * Removes the last sub-build layer from the node builder.
  34264. *
  34265. * @return {SubBuildNode} The removed sub-build layer.
  34266. */
  34267. removeSubBuild() {
  34268. return this.subBuildLayers.pop();
  34269. }
  34270. /**
  34271. * Returns the closest sub-build layer for the given data.
  34272. *
  34273. * @param {Node|Set|Array} data - The data to get the closest sub-build layer from.
  34274. * @return {?string} The closest sub-build name or null if none found.
  34275. */
  34276. getClosestSubBuild( data ) {
  34277. let subBuilds;
  34278. if ( data && data.isNode ) {
  34279. if ( data.isShaderCallNodeInternal ) {
  34280. subBuilds = data.shaderNode.subBuilds;
  34281. } else if ( data.isStackNode ) {
  34282. subBuilds = [ data.subBuild ];
  34283. } else {
  34284. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  34285. }
  34286. } else if ( data instanceof Set ) {
  34287. subBuilds = [ ...data ];
  34288. } else {
  34289. subBuilds = data;
  34290. }
  34291. if ( ! subBuilds ) return null;
  34292. const subBuildLayers = this.subBuildLayers;
  34293. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  34294. const subBuild = subBuilds[ i ];
  34295. if ( subBuildLayers.includes( subBuild ) ) {
  34296. return subBuild;
  34297. }
  34298. }
  34299. return null;
  34300. }
  34301. /**
  34302. * Returns the output node of a sub-build layer.
  34303. *
  34304. * @param {Node} node - The node to get the output from.
  34305. * @return {string} The output node name.
  34306. */
  34307. getSubBuildOutput( node ) {
  34308. return this.getSubBuildProperty( 'outputNode', node );
  34309. }
  34310. /**
  34311. * Returns the sub-build property name for the given property and node.
  34312. *
  34313. * @param {string} [property=''] - The property name.
  34314. * @param {?Node} [node=null] - The node to get the sub-build from.
  34315. * @return {string} The sub-build property name.
  34316. */
  34317. getSubBuildProperty( property = '', node = null ) {
  34318. let subBuild;
  34319. if ( node !== null ) {
  34320. subBuild = this.getClosestSubBuild( node );
  34321. } else {
  34322. subBuild = this.subBuildFn;
  34323. }
  34324. let result;
  34325. if ( subBuild ) {
  34326. result = property ? ( subBuild + '_' + property ) : subBuild;
  34327. } else {
  34328. result = property;
  34329. }
  34330. return result;
  34331. }
  34332. /**
  34333. * Central build method which controls the build for the given object.
  34334. *
  34335. * @return {NodeBuilder} A reference to this node builder.
  34336. */
  34337. build() {
  34338. const { object, material, renderer } = this;
  34339. if ( material !== null ) {
  34340. let nodeMaterial = renderer.library.fromMaterial( material );
  34341. if ( nodeMaterial === null ) {
  34342. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  34343. nodeMaterial = new NodeMaterial();
  34344. }
  34345. nodeMaterial.build( this );
  34346. } else {
  34347. this.addFlow( 'compute', object );
  34348. }
  34349. // setup() -> stage 1: create possible new nodes and returns an output reference node
  34350. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  34351. // generate() -> stage 3: generate shader
  34352. for ( const buildStage of defaultBuildStages ) {
  34353. this.setBuildStage( buildStage );
  34354. if ( this.context.vertex && this.context.vertex.isNode ) {
  34355. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  34356. }
  34357. for ( const shaderStage of shaderStages ) {
  34358. this.setShaderStage( shaderStage );
  34359. const flowNodes = this.flowNodes[ shaderStage ];
  34360. for ( const node of flowNodes ) {
  34361. if ( buildStage === 'generate' ) {
  34362. this.flowNode( node );
  34363. } else {
  34364. node.build( this );
  34365. }
  34366. }
  34367. }
  34368. }
  34369. this.setBuildStage( null );
  34370. this.setShaderStage( null );
  34371. // stage 4: build code for a specific output
  34372. this.buildCode();
  34373. this.buildUpdateNodes();
  34374. return this;
  34375. }
  34376. /**
  34377. * Returns a uniform representation which is later used for UBO generation and rendering.
  34378. *
  34379. * @param {NodeUniform} uniformNode - The uniform node.
  34380. * @param {string} type - The requested type.
  34381. * @return {Uniform} The uniform.
  34382. */
  34383. getNodeUniform( uniformNode, type ) {
  34384. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  34385. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  34386. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  34387. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  34388. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  34389. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  34390. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  34391. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  34392. throw new Error( `Uniform "${type}" not declared.` );
  34393. }
  34394. /**
  34395. * Formats the given shader snippet from a given type into another one. E.g.
  34396. * this method might be used to convert a simple float string `"1.0"` into a
  34397. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  34398. *
  34399. * @param {string} snippet - The shader snippet.
  34400. * @param {string} fromType - The source type.
  34401. * @param {string} toType - The target type.
  34402. * @return {string} The updated shader string.
  34403. */
  34404. format( snippet, fromType, toType ) {
  34405. fromType = this.getVectorType( fromType );
  34406. toType = this.getVectorType( toType );
  34407. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  34408. return snippet;
  34409. }
  34410. const fromTypeLength = this.getTypeLength( fromType );
  34411. const toTypeLength = this.getTypeLength( toType );
  34412. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  34413. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  34414. }
  34415. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  34416. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  34417. }
  34418. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  34419. // @TODO: ignore for now
  34420. return snippet;
  34421. }
  34422. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  34423. // @TODO: ignore for now
  34424. return snippet;
  34425. }
  34426. if ( fromTypeLength === toTypeLength ) {
  34427. return `${ this.getType( toType ) }( ${ snippet } )`;
  34428. }
  34429. if ( fromTypeLength > toTypeLength ) {
  34430. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  34431. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  34432. }
  34433. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  34434. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  34435. }
  34436. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  34437. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  34438. }
  34439. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  34440. // convert a number value to vector type, e.g:
  34441. // vec3( 1u ) -> vec3( float( 1u ) )
  34442. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  34443. }
  34444. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  34445. }
  34446. /**
  34447. * Returns a signature with the engine's current revision.
  34448. *
  34449. * @return {string} The signature.
  34450. */
  34451. getSignature() {
  34452. return `// Three.js r${ REVISION } - Node System\n`;
  34453. }
  34454. /**
  34455. * Prevents the node builder from being used as an iterable in TSL.Fn(), avoiding potential runtime errors.
  34456. */
  34457. *[ Symbol.iterator ]() { }
  34458. }
  34459. /**
  34460. * Management class for updating nodes. The module tracks metrics like
  34461. * the elapsed time, delta time, the render and frame ID to correctly
  34462. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  34463. * and {@link Node#updateAfter} depending on the node's configuration.
  34464. */
  34465. class NodeFrame {
  34466. /**
  34467. * Constructs a new node fame.
  34468. */
  34469. constructor() {
  34470. /**
  34471. * The elapsed time in seconds.
  34472. *
  34473. * @type {number}
  34474. * @default 0
  34475. */
  34476. this.time = 0;
  34477. /**
  34478. * The delta time in seconds.
  34479. *
  34480. * @type {number}
  34481. * @default 0
  34482. */
  34483. this.deltaTime = 0;
  34484. /**
  34485. * The frame ID.
  34486. *
  34487. * @type {number}
  34488. * @default 0
  34489. */
  34490. this.frameId = 0;
  34491. /**
  34492. * The render ID.
  34493. *
  34494. * @type {number}
  34495. * @default 0
  34496. */
  34497. this.renderId = 0;
  34498. /**
  34499. * Used to control the {@link Node#update} call.
  34500. *
  34501. * @type {WeakMap<Node, Object>}
  34502. */
  34503. this.updateMap = new WeakMap();
  34504. /**
  34505. * Used to control the {@link Node#updateBefore} call.
  34506. *
  34507. * @type {WeakMap<Node, Object>}
  34508. */
  34509. this.updateBeforeMap = new WeakMap();
  34510. /**
  34511. * Used to control the {@link Node#updateAfter} call.
  34512. *
  34513. * @type {WeakMap<Node, Object>}
  34514. */
  34515. this.updateAfterMap = new WeakMap();
  34516. /**
  34517. * A reference to the current renderer.
  34518. *
  34519. * @type {?Renderer}
  34520. * @default null
  34521. */
  34522. this.renderer = null;
  34523. /**
  34524. * A reference to the current material.
  34525. *
  34526. * @type {?Material}
  34527. * @default null
  34528. */
  34529. this.material = null;
  34530. /**
  34531. * A reference to the current camera.
  34532. *
  34533. * @type {?Camera}
  34534. * @default null
  34535. */
  34536. this.camera = null;
  34537. /**
  34538. * A reference to the current 3D object.
  34539. *
  34540. * @type {?Object3D}
  34541. * @default null
  34542. */
  34543. this.object = null;
  34544. /**
  34545. * A reference to the current scene.
  34546. *
  34547. * @type {?Scene}
  34548. * @default null
  34549. */
  34550. this.scene = null;
  34551. }
  34552. /**
  34553. * Returns a dictionary for a given node and update map which
  34554. * is used to correctly call node update methods per frame or render.
  34555. *
  34556. * @private
  34557. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  34558. * @param {Node} nodeRef - The reference to the current node.
  34559. * @return {Object<string,WeakMap>} The dictionary.
  34560. */
  34561. _getMaps( referenceMap, nodeRef ) {
  34562. let maps = referenceMap.get( nodeRef );
  34563. if ( maps === undefined ) {
  34564. maps = {
  34565. renderMap: new WeakMap(),
  34566. frameMap: new WeakMap()
  34567. };
  34568. referenceMap.set( nodeRef, maps );
  34569. }
  34570. return maps;
  34571. }
  34572. /**
  34573. * This method executes the {@link Node#updateBefore} for the given node.
  34574. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  34575. * is only executed once per frame, render or object depending on the update
  34576. * type.
  34577. *
  34578. * @param {Node} node - The node that should be updated.
  34579. */
  34580. updateBeforeNode( node ) {
  34581. const updateType = node.getUpdateBeforeType();
  34582. const reference = node.updateReference( this );
  34583. if ( updateType === NodeUpdateType.FRAME ) {
  34584. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  34585. if ( frameMap.get( reference ) !== this.frameId ) {
  34586. if ( node.updateBefore( this ) !== false ) {
  34587. frameMap.set( reference, this.frameId );
  34588. }
  34589. }
  34590. } else if ( updateType === NodeUpdateType.RENDER ) {
  34591. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  34592. if ( renderMap.get( reference ) !== this.renderId ) {
  34593. if ( node.updateBefore( this ) !== false ) {
  34594. renderMap.set( reference, this.renderId );
  34595. }
  34596. }
  34597. } else if ( updateType === NodeUpdateType.OBJECT ) {
  34598. node.updateBefore( this );
  34599. }
  34600. }
  34601. /**
  34602. * This method executes the {@link Node#updateAfter} for the given node.
  34603. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  34604. * is only executed once per frame, render or object depending on the update
  34605. * type.
  34606. *
  34607. * @param {Node} node - The node that should be updated.
  34608. */
  34609. updateAfterNode( node ) {
  34610. const updateType = node.getUpdateAfterType();
  34611. const reference = node.updateReference( this );
  34612. if ( updateType === NodeUpdateType.FRAME ) {
  34613. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  34614. if ( frameMap.get( reference ) !== this.frameId ) {
  34615. if ( node.updateAfter( this ) !== false ) {
  34616. frameMap.set( reference, this.frameId );
  34617. }
  34618. }
  34619. } else if ( updateType === NodeUpdateType.RENDER ) {
  34620. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  34621. if ( renderMap.get( reference ) !== this.renderId ) {
  34622. if ( node.updateAfter( this ) !== false ) {
  34623. renderMap.set( reference, this.renderId );
  34624. }
  34625. }
  34626. } else if ( updateType === NodeUpdateType.OBJECT ) {
  34627. node.updateAfter( this );
  34628. }
  34629. }
  34630. /**
  34631. * This method executes the {@link Node#update} for the given node.
  34632. * It makes sure {@link Node#updateType} is honored meaning the update
  34633. * is only executed once per frame, render or object depending on the update
  34634. * type.
  34635. *
  34636. * @param {Node} node - The node that should be updated.
  34637. */
  34638. updateNode( node ) {
  34639. const updateType = node.getUpdateType();
  34640. const reference = node.updateReference( this );
  34641. if ( updateType === NodeUpdateType.FRAME ) {
  34642. const { frameMap } = this._getMaps( this.updateMap, reference );
  34643. if ( frameMap.get( reference ) !== this.frameId ) {
  34644. if ( node.update( this ) !== false ) {
  34645. frameMap.set( reference, this.frameId );
  34646. }
  34647. }
  34648. } else if ( updateType === NodeUpdateType.RENDER ) {
  34649. const { renderMap } = this._getMaps( this.updateMap, reference );
  34650. if ( renderMap.get( reference ) !== this.renderId ) {
  34651. if ( node.update( this ) !== false ) {
  34652. renderMap.set( reference, this.renderId );
  34653. }
  34654. }
  34655. } else if ( updateType === NodeUpdateType.OBJECT ) {
  34656. node.update( this );
  34657. }
  34658. }
  34659. /**
  34660. * Updates the internal state of the node frame. This method is
  34661. * called by the renderer in its internal animation loop.
  34662. */
  34663. update() {
  34664. this.frameId ++;
  34665. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  34666. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  34667. this.lastTime = performance.now();
  34668. this.time += this.deltaTime;
  34669. }
  34670. }
  34671. /**
  34672. * Describes the input of a {@link NodeFunction}.
  34673. */
  34674. class NodeFunctionInput {
  34675. /**
  34676. * Constructs a new node function input.
  34677. *
  34678. * @param {string} type - The input type.
  34679. * @param {string} name - The input name.
  34680. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  34681. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  34682. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  34683. */
  34684. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  34685. /**
  34686. * The input type.
  34687. *
  34688. * @type {string}
  34689. */
  34690. this.type = type;
  34691. /**
  34692. * The input name.
  34693. *
  34694. * @type {string}
  34695. */
  34696. this.name = name;
  34697. /**
  34698. * If the input is an Array, count will be the length.
  34699. *
  34700. * @type {?number}
  34701. * @default null
  34702. */
  34703. this.count = count;
  34704. /**
  34705. *The parameter qualifier (only relevant for GLSL).
  34706. *
  34707. * @type {('in'|'out'|'inout')}
  34708. * @default ''
  34709. */
  34710. this.qualifier = qualifier;
  34711. /**
  34712. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  34713. *
  34714. * @type {boolean}
  34715. * @default false
  34716. */
  34717. this.isConst = isConst;
  34718. }
  34719. }
  34720. NodeFunctionInput.isNodeFunctionInput = true;
  34721. /**
  34722. * Module for representing directional lights as nodes.
  34723. *
  34724. * @augments AnalyticLightNode
  34725. */
  34726. class DirectionalLightNode extends AnalyticLightNode {
  34727. static get type() {
  34728. return 'DirectionalLightNode';
  34729. }
  34730. /**
  34731. * Constructs a new directional light node.
  34732. *
  34733. * @param {?DirectionalLight} [light=null] - The directional light source.
  34734. */
  34735. constructor( light = null ) {
  34736. super( light );
  34737. }
  34738. setupDirect() {
  34739. const lightColor = this.colorNode;
  34740. const lightDirection = lightTargetDirection( this.light );
  34741. return { lightDirection, lightColor };
  34742. }
  34743. }
  34744. const _matrix41 = /*@__PURE__*/ new Matrix4();
  34745. const _matrix42 = /*@__PURE__*/ new Matrix4();
  34746. let _ltcLib = null;
  34747. /**
  34748. * Module for representing rect area lights as nodes.
  34749. *
  34750. * @augments AnalyticLightNode
  34751. */
  34752. class RectAreaLightNode extends AnalyticLightNode {
  34753. static get type() {
  34754. return 'RectAreaLightNode';
  34755. }
  34756. /**
  34757. * Constructs a new rect area light node.
  34758. *
  34759. * @param {?RectAreaLight} [light=null] - The rect area light source.
  34760. */
  34761. constructor( light = null ) {
  34762. super( light );
  34763. /**
  34764. * Uniform node representing the half height of the are light.
  34765. *
  34766. * @type {UniformNode<vec3>}
  34767. */
  34768. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  34769. /**
  34770. * Uniform node representing the half width of the are light.
  34771. *
  34772. * @type {UniformNode<vec3>}
  34773. */
  34774. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  34775. /**
  34776. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  34777. * relies on `viewMatrix` which might vary per render call.
  34778. *
  34779. * @type {string}
  34780. * @default 'render'
  34781. */
  34782. this.updateType = NodeUpdateType.RENDER;
  34783. }
  34784. /**
  34785. * Overwritten to updated rect area light specific uniforms.
  34786. *
  34787. * @param {NodeFrame} frame - A reference to the current node frame.
  34788. */
  34789. update( frame ) {
  34790. super.update( frame );
  34791. const { light } = this;
  34792. const viewMatrix = frame.camera.matrixWorldInverse;
  34793. _matrix42.identity();
  34794. _matrix41.copy( light.matrixWorld );
  34795. _matrix41.premultiply( viewMatrix );
  34796. _matrix42.extractRotation( _matrix41 );
  34797. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  34798. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  34799. this.halfWidth.value.applyMatrix4( _matrix42 );
  34800. this.halfHeight.value.applyMatrix4( _matrix42 );
  34801. }
  34802. setupDirectRectArea( builder ) {
  34803. let ltc_1, ltc_2;
  34804. if ( builder.isAvailable( 'float32Filterable' ) ) {
  34805. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  34806. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  34807. } else {
  34808. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  34809. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  34810. }
  34811. const { colorNode, light } = this;
  34812. const lightPosition = lightViewPosition( light );
  34813. return {
  34814. lightColor: colorNode,
  34815. lightPosition,
  34816. halfWidth: this.halfWidth,
  34817. halfHeight: this.halfHeight,
  34818. ltc_1,
  34819. ltc_2
  34820. };
  34821. }
  34822. /**
  34823. * Used to configure the internal BRDF approximation texture data.
  34824. *
  34825. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  34826. */
  34827. static setLTC( ltc ) {
  34828. _ltcLib = ltc;
  34829. }
  34830. }
  34831. /**
  34832. * Module for representing spot lights as nodes.
  34833. *
  34834. * @augments AnalyticLightNode
  34835. */
  34836. class SpotLightNode extends AnalyticLightNode {
  34837. static get type() {
  34838. return 'SpotLightNode';
  34839. }
  34840. /**
  34841. * Constructs a new spot light node.
  34842. *
  34843. * @param {?SpotLight} [light=null] - The spot light source.
  34844. */
  34845. constructor( light = null ) {
  34846. super( light );
  34847. /**
  34848. * Uniform node representing the cone cosine.
  34849. *
  34850. * @type {UniformNode<float>}
  34851. */
  34852. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  34853. /**
  34854. * Uniform node representing the penumbra cosine.
  34855. *
  34856. * @type {UniformNode<float>}
  34857. */
  34858. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  34859. /**
  34860. * Uniform node representing the cutoff distance.
  34861. *
  34862. * @type {UniformNode<float>}
  34863. */
  34864. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  34865. /**
  34866. * Uniform node representing the decay exponent.
  34867. *
  34868. * @type {UniformNode<float>}
  34869. */
  34870. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  34871. /**
  34872. * Uniform node representing the light color.
  34873. *
  34874. * @type {UniformNode<Color>}
  34875. */
  34876. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  34877. }
  34878. /**
  34879. * Overwritten to updated spot light specific uniforms.
  34880. *
  34881. * @param {NodeFrame} frame - A reference to the current node frame.
  34882. */
  34883. update( frame ) {
  34884. super.update( frame );
  34885. const { light } = this;
  34886. this.coneCosNode.value = Math.cos( light.angle );
  34887. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  34888. this.cutoffDistanceNode.value = light.distance;
  34889. this.decayExponentNode.value = light.decay;
  34890. }
  34891. /**
  34892. * Computes the spot attenuation for the given angle.
  34893. *
  34894. * @param {NodeBuilder} builder - The node builder.
  34895. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  34896. * @return {Node<float>} The spot attenuation.
  34897. */
  34898. getSpotAttenuation( builder, angleCosine ) {
  34899. const { coneCosNode, penumbraCosNode } = this;
  34900. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  34901. }
  34902. getLightCoord( builder ) {
  34903. const properties = builder.getNodeProperties( this );
  34904. let projectionUV = properties.projectionUV;
  34905. if ( projectionUV === undefined ) {
  34906. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  34907. properties.projectionUV = projectionUV;
  34908. }
  34909. return projectionUV;
  34910. }
  34911. setupDirect( builder ) {
  34912. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  34913. const lightVector = this.getLightVector( builder );
  34914. const lightDirection = lightVector.normalize();
  34915. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  34916. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  34917. const lightDistance = lightVector.length();
  34918. const lightAttenuation = getDistanceAttenuation( {
  34919. lightDistance,
  34920. cutoffDistance: cutoffDistanceNode,
  34921. decayExponent: decayExponentNode
  34922. } );
  34923. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  34924. let projected, lightCoord;
  34925. if ( light.colorNode ) {
  34926. lightCoord = this.getLightCoord( builder );
  34927. projected = light.colorNode( lightCoord );
  34928. } else if ( light.map ) {
  34929. lightCoord = this.getLightCoord( builder );
  34930. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  34931. }
  34932. if ( projected ) {
  34933. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  34934. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  34935. }
  34936. return { lightColor, lightDirection };
  34937. }
  34938. }
  34939. /**
  34940. * An IES version of the default spot light node.
  34941. *
  34942. * @augments SpotLightNode
  34943. */
  34944. class IESSpotLightNode extends SpotLightNode {
  34945. static get type() {
  34946. return 'IESSpotLightNode';
  34947. }
  34948. /**
  34949. * Overwrites the default implementation to compute an IES conform spot attenuation.
  34950. *
  34951. * @param {NodeBuilder} builder - The node builder.
  34952. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  34953. * @return {Node<float>} The spot attenuation.
  34954. */
  34955. getSpotAttenuation( builder, angleCosine ) {
  34956. const iesMap = this.light.iesMap;
  34957. let spotAttenuation = null;
  34958. if ( iesMap && iesMap.isTexture === true ) {
  34959. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  34960. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  34961. } else {
  34962. spotAttenuation = super.getSpotAttenuation( angleCosine );
  34963. }
  34964. return spotAttenuation;
  34965. }
  34966. }
  34967. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  34968. const d = p.abs().sub( b );
  34969. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  34970. } );
  34971. /**
  34972. * An implementation of a projector light node.
  34973. *
  34974. * @augments SpotLightNode
  34975. */
  34976. class ProjectorLightNode extends SpotLightNode {
  34977. static get type() {
  34978. return 'ProjectorLightNode';
  34979. }
  34980. update( frame ) {
  34981. super.update( frame );
  34982. const light = this.light;
  34983. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  34984. if ( light.aspect === null ) {
  34985. let aspect = 1;
  34986. if ( light.map !== null ) {
  34987. aspect = light.map.width / light.map.height;
  34988. }
  34989. light.shadow.aspect = aspect;
  34990. } else {
  34991. light.shadow.aspect = light.aspect;
  34992. }
  34993. }
  34994. /**
  34995. * Overwrites the default implementation to compute projection attenuation.
  34996. *
  34997. * @param {NodeBuilder} builder - The node builder.
  34998. * @return {Node<float>} The spot attenuation.
  34999. */
  35000. getSpotAttenuation( builder ) {
  35001. const attenuation = float( 0 );
  35002. const penumbraCos = this.penumbraCosNode;
  35003. // compute the fragment's position in the light's clip space
  35004. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  35005. // the sign of w determines whether the current fragment is in front or behind the light.
  35006. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  35007. If( spotLightCoord.w.greaterThan( 0 ), () => {
  35008. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  35009. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  35010. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  35011. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  35012. } );
  35013. return attenuation;
  35014. }
  35015. }
  35016. /**
  35017. * Module for representing ambient lights as nodes.
  35018. *
  35019. * @augments AnalyticLightNode
  35020. */
  35021. class AmbientLightNode extends AnalyticLightNode {
  35022. static get type() {
  35023. return 'AmbientLightNode';
  35024. }
  35025. /**
  35026. * Constructs a new ambient light node.
  35027. *
  35028. * @param {?AmbientLight} [light=null] - The ambient light source.
  35029. */
  35030. constructor( light = null ) {
  35031. super( light );
  35032. }
  35033. setup( { context } ) {
  35034. context.irradiance.addAssign( this.colorNode );
  35035. }
  35036. }
  35037. /**
  35038. * Module for representing hemisphere lights as nodes.
  35039. *
  35040. * @augments AnalyticLightNode
  35041. */
  35042. class HemisphereLightNode extends AnalyticLightNode {
  35043. static get type() {
  35044. return 'HemisphereLightNode';
  35045. }
  35046. /**
  35047. * Constructs a new hemisphere light node.
  35048. *
  35049. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  35050. */
  35051. constructor( light = null ) {
  35052. super( light );
  35053. /**
  35054. * Uniform node representing the light's position.
  35055. *
  35056. * @type {UniformNode<vec3>}
  35057. */
  35058. this.lightPositionNode = lightPosition( light );
  35059. /**
  35060. * A node representing the light's direction.
  35061. *
  35062. * @type {Node<vec3>}
  35063. */
  35064. this.lightDirectionNode = this.lightPositionNode.normalize();
  35065. /**
  35066. * Uniform node representing the light's ground color.
  35067. *
  35068. * @type {UniformNode<vec3>}
  35069. */
  35070. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  35071. }
  35072. /**
  35073. * Overwritten to updated hemisphere light specific uniforms.
  35074. *
  35075. * @param {NodeFrame} frame - A reference to the current node frame.
  35076. */
  35077. update( frame ) {
  35078. const { light } = this;
  35079. super.update( frame );
  35080. this.lightPositionNode.object3d = light;
  35081. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  35082. }
  35083. setup( builder ) {
  35084. const { colorNode, groundColorNode, lightDirectionNode } = this;
  35085. const dotNL = normalWorld.dot( lightDirectionNode );
  35086. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  35087. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  35088. builder.context.irradiance.addAssign( irradiance );
  35089. }
  35090. }
  35091. /**
  35092. * Module for representing light probes as nodes.
  35093. *
  35094. * @augments AnalyticLightNode
  35095. */
  35096. class LightProbeNode extends AnalyticLightNode {
  35097. static get type() {
  35098. return 'LightProbeNode';
  35099. }
  35100. /**
  35101. * Constructs a new light probe node.
  35102. *
  35103. * @param {?LightProbe} [light=null] - The light probe.
  35104. */
  35105. constructor( light = null ) {
  35106. super( light );
  35107. const array = [];
  35108. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  35109. /**
  35110. * Light probe represented as a uniform of spherical harmonics.
  35111. *
  35112. * @type {UniformArrayNode}
  35113. */
  35114. this.lightProbe = uniformArray( array );
  35115. }
  35116. /**
  35117. * Overwritten to updated light probe specific uniforms.
  35118. *
  35119. * @param {NodeFrame} frame - A reference to the current node frame.
  35120. */
  35121. update( frame ) {
  35122. const { light } = this;
  35123. super.update( frame );
  35124. //
  35125. for ( let i = 0; i < 9; i ++ ) {
  35126. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  35127. }
  35128. }
  35129. setup( builder ) {
  35130. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  35131. builder.context.irradiance.addAssign( irradiance );
  35132. }
  35133. }
  35134. /**
  35135. * Base class for node parsers. A derived parser must be implemented
  35136. * for each supported native shader language.
  35137. */
  35138. class NodeParser {
  35139. /**
  35140. * The method parses the given native code an returns a node function.
  35141. *
  35142. * @abstract
  35143. * @param {string} source - The native shader code.
  35144. * @return {NodeFunction} A node function.
  35145. */
  35146. parseFunction( /*source*/ ) {
  35147. console.warn( 'Abstract function.' );
  35148. }
  35149. }
  35150. /**
  35151. * Base class for node functions. A derived module must be implemented
  35152. * for each supported native shader language. Similar to other `Node*` modules,
  35153. * this class is only relevant during the building process and not used
  35154. * in user-level code.
  35155. */
  35156. class NodeFunction {
  35157. /**
  35158. * Constructs a new node function.
  35159. *
  35160. * @param {string} type - The node type. This type is the return type of the node function.
  35161. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  35162. * @param {string} [name=''] - The function's name.
  35163. * @param {string} [precision=''] - The precision qualifier.
  35164. */
  35165. constructor( type, inputs, name = '', precision = '' ) {
  35166. /**
  35167. * The node type. This type is the return type of the node function.
  35168. *
  35169. * @type {string}
  35170. */
  35171. this.type = type;
  35172. /**
  35173. * The function's inputs.
  35174. *
  35175. * @type {Array<NodeFunctionInput>}
  35176. */
  35177. this.inputs = inputs;
  35178. /**
  35179. * The name of the uniform.
  35180. *
  35181. * @type {string}
  35182. * @default ''
  35183. */
  35184. this.name = name;
  35185. /**
  35186. * The precision qualifier.
  35187. *
  35188. * @type {string}
  35189. * @default ''
  35190. */
  35191. this.precision = precision;
  35192. }
  35193. /**
  35194. * This method returns the native code of the node function.
  35195. *
  35196. * @abstract
  35197. * @param {string} name - The function's name.
  35198. * @return {string} A shader code.
  35199. */
  35200. getCode( /*name = this.name*/ ) {
  35201. console.warn( 'Abstract function.' );
  35202. }
  35203. }
  35204. NodeFunction.isNodeFunction = true;
  35205. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  35206. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  35207. const pragmaMain = '#pragma main';
  35208. const parse$1 = ( source ) => {
  35209. source = source.trim();
  35210. const pragmaMainIndex = source.indexOf( pragmaMain );
  35211. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  35212. const declaration = mainCode.match( declarationRegexp$1 );
  35213. if ( declaration !== null && declaration.length === 5 ) {
  35214. // tokenizer
  35215. const inputsCode = declaration[ 4 ];
  35216. const propsMatches = [];
  35217. let nameMatch = null;
  35218. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  35219. propsMatches.push( nameMatch );
  35220. }
  35221. // parser
  35222. const inputs = [];
  35223. let i = 0;
  35224. while ( i < propsMatches.length ) {
  35225. const isConst = propsMatches[ i ][ 0 ] === 'const';
  35226. if ( isConst === true ) {
  35227. i ++;
  35228. }
  35229. let qualifier = propsMatches[ i ][ 0 ];
  35230. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  35231. i ++;
  35232. } else {
  35233. qualifier = '';
  35234. }
  35235. const type = propsMatches[ i ++ ][ 0 ];
  35236. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  35237. if ( Number.isNaN( count ) === false ) i ++;
  35238. else count = null;
  35239. const name = propsMatches[ i ++ ][ 0 ];
  35240. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  35241. }
  35242. //
  35243. const blockCode = mainCode.substring( declaration[ 0 ].length );
  35244. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  35245. const type = declaration[ 2 ];
  35246. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  35247. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  35248. return {
  35249. type,
  35250. inputs,
  35251. name,
  35252. precision,
  35253. inputsCode,
  35254. blockCode,
  35255. headerCode
  35256. };
  35257. } else {
  35258. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  35259. }
  35260. };
  35261. /**
  35262. * This class represents a GLSL node function.
  35263. *
  35264. * @augments NodeFunction
  35265. */
  35266. class GLSLNodeFunction extends NodeFunction {
  35267. /**
  35268. * Constructs a new GLSL node function.
  35269. *
  35270. * @param {string} source - The GLSL source.
  35271. */
  35272. constructor( source ) {
  35273. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  35274. super( type, inputs, name, precision );
  35275. this.inputsCode = inputsCode;
  35276. this.blockCode = blockCode;
  35277. this.headerCode = headerCode;
  35278. }
  35279. /**
  35280. * This method returns the GLSL code of the node function.
  35281. *
  35282. * @param {string} [name=this.name] - The function's name.
  35283. * @return {string} The shader code.
  35284. */
  35285. getCode( name = this.name ) {
  35286. let code;
  35287. const blockCode = this.blockCode;
  35288. if ( blockCode !== '' ) {
  35289. const { type, inputsCode, headerCode, precision } = this;
  35290. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  35291. if ( precision !== '' ) {
  35292. declarationCode = `${ precision } ${ declarationCode }`;
  35293. }
  35294. code = headerCode + declarationCode + blockCode;
  35295. } else {
  35296. // interface function
  35297. code = '';
  35298. }
  35299. return code;
  35300. }
  35301. }
  35302. /**
  35303. * A GLSL node parser.
  35304. *
  35305. * @augments NodeParser
  35306. */
  35307. class GLSLNodeParser extends NodeParser {
  35308. /**
  35309. * The method parses the given GLSL code an returns a node function.
  35310. *
  35311. * @param {string} source - The GLSL code.
  35312. * @return {GLSLNodeFunction} A node function.
  35313. */
  35314. parseFunction( source ) {
  35315. return new GLSLNodeFunction( source );
  35316. }
  35317. }
  35318. const _outputNodeMap = new WeakMap();
  35319. const _chainKeys$2 = [];
  35320. const _cacheKeyValues = [];
  35321. /**
  35322. * This renderer module manages node-related objects and is the
  35323. * primary interface between the renderer and the node system.
  35324. *
  35325. * @private
  35326. * @augments DataMap
  35327. */
  35328. class Nodes extends DataMap {
  35329. /**
  35330. * Constructs a new nodes management component.
  35331. *
  35332. * @param {Renderer} renderer - The renderer.
  35333. * @param {Backend} backend - The renderer's backend.
  35334. */
  35335. constructor( renderer, backend ) {
  35336. super();
  35337. /**
  35338. * The renderer.
  35339. *
  35340. * @type {Renderer}
  35341. */
  35342. this.renderer = renderer;
  35343. /**
  35344. * The renderer's backend.
  35345. *
  35346. * @type {Backend}
  35347. */
  35348. this.backend = backend;
  35349. /**
  35350. * The node frame.
  35351. *
  35352. * @type {Renderer}
  35353. */
  35354. this.nodeFrame = new NodeFrame();
  35355. /**
  35356. * A cache for managing node builder states.
  35357. *
  35358. * @type {Map<number,NodeBuilderState>}
  35359. */
  35360. this.nodeBuilderCache = new Map();
  35361. /**
  35362. * A cache for managing data cache key data.
  35363. *
  35364. * @type {ChainMap}
  35365. */
  35366. this.callHashCache = new ChainMap();
  35367. /**
  35368. * A cache for managing node uniforms group data.
  35369. *
  35370. * @type {ChainMap}
  35371. */
  35372. this.groupsData = new ChainMap();
  35373. /**
  35374. * A cache for managing node objects of
  35375. * scene properties like fog or environments.
  35376. *
  35377. * @type {Object<string,WeakMap>}
  35378. */
  35379. this.cacheLib = {};
  35380. }
  35381. /**
  35382. * Returns `true` if the given node uniforms group must be updated or not.
  35383. *
  35384. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  35385. * @return {boolean} Whether the node uniforms group requires an update or not.
  35386. */
  35387. updateGroup( nodeUniformsGroup ) {
  35388. const groupNode = nodeUniformsGroup.groupNode;
  35389. const name = groupNode.name;
  35390. // objectGroup is always updated
  35391. if ( name === objectGroup.name ) return true;
  35392. // renderGroup is updated once per render/compute call
  35393. if ( name === renderGroup.name ) {
  35394. const uniformsGroupData = this.get( nodeUniformsGroup );
  35395. const renderId = this.nodeFrame.renderId;
  35396. if ( uniformsGroupData.renderId !== renderId ) {
  35397. uniformsGroupData.renderId = renderId;
  35398. return true;
  35399. }
  35400. return false;
  35401. }
  35402. // frameGroup is updated once per frame
  35403. if ( name === frameGroup.name ) {
  35404. const uniformsGroupData = this.get( nodeUniformsGroup );
  35405. const frameId = this.nodeFrame.frameId;
  35406. if ( uniformsGroupData.frameId !== frameId ) {
  35407. uniformsGroupData.frameId = frameId;
  35408. return true;
  35409. }
  35410. return false;
  35411. }
  35412. // other groups are updated just when groupNode.needsUpdate is true
  35413. _chainKeys$2[ 0 ] = groupNode;
  35414. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  35415. let groupData = this.groupsData.get( _chainKeys$2 );
  35416. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  35417. _chainKeys$2.length = 0;
  35418. if ( groupData.version !== groupNode.version ) {
  35419. groupData.version = groupNode.version;
  35420. return true;
  35421. }
  35422. return false;
  35423. }
  35424. /**
  35425. * Returns the cache key for the given render object.
  35426. *
  35427. * @param {RenderObject} renderObject - The render object.
  35428. * @return {number} The cache key.
  35429. */
  35430. getForRenderCacheKey( renderObject ) {
  35431. return renderObject.initialCacheKey;
  35432. }
  35433. /**
  35434. * Returns a node builder state for the given render object.
  35435. *
  35436. * @param {RenderObject} renderObject - The render object.
  35437. * @return {NodeBuilderState} The node builder state.
  35438. */
  35439. getForRender( renderObject ) {
  35440. const renderObjectData = this.get( renderObject );
  35441. let nodeBuilderState = renderObjectData.nodeBuilderState;
  35442. if ( nodeBuilderState === undefined ) {
  35443. const { nodeBuilderCache } = this;
  35444. const cacheKey = this.getForRenderCacheKey( renderObject );
  35445. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  35446. if ( nodeBuilderState === undefined ) {
  35447. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  35448. nodeBuilder.scene = renderObject.scene;
  35449. nodeBuilder.material = renderObject.material;
  35450. nodeBuilder.camera = renderObject.camera;
  35451. nodeBuilder.context.material = renderObject.material;
  35452. nodeBuilder.lightsNode = renderObject.lightsNode;
  35453. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  35454. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  35455. nodeBuilder.clippingContext = renderObject.clippingContext;
  35456. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  35457. nodeBuilder.enableMultiview();
  35458. }
  35459. nodeBuilder.build();
  35460. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35461. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  35462. }
  35463. nodeBuilderState.usedTimes ++;
  35464. renderObjectData.nodeBuilderState = nodeBuilderState;
  35465. }
  35466. return nodeBuilderState;
  35467. }
  35468. /**
  35469. * Deletes the given object from the internal data map
  35470. *
  35471. * @param {any} object - The object to delete.
  35472. * @return {?Object} The deleted dictionary.
  35473. */
  35474. delete( object ) {
  35475. if ( object.isRenderObject ) {
  35476. const nodeBuilderState = this.get( object ).nodeBuilderState;
  35477. nodeBuilderState.usedTimes --;
  35478. if ( nodeBuilderState.usedTimes === 0 ) {
  35479. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  35480. }
  35481. }
  35482. return super.delete( object );
  35483. }
  35484. /**
  35485. * Returns a node builder state for the given compute node.
  35486. *
  35487. * @param {Node} computeNode - The compute node.
  35488. * @return {NodeBuilderState} The node builder state.
  35489. */
  35490. getForCompute( computeNode ) {
  35491. const computeData = this.get( computeNode );
  35492. let nodeBuilderState = computeData.nodeBuilderState;
  35493. if ( nodeBuilderState === undefined ) {
  35494. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  35495. nodeBuilder.build();
  35496. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35497. computeData.nodeBuilderState = nodeBuilderState;
  35498. }
  35499. return nodeBuilderState;
  35500. }
  35501. /**
  35502. * Creates a node builder state for the given node builder.
  35503. *
  35504. * @private
  35505. * @param {NodeBuilder} nodeBuilder - The node builder.
  35506. * @return {NodeBuilderState} The node builder state.
  35507. */
  35508. _createNodeBuilderState( nodeBuilder ) {
  35509. return new NodeBuilderState(
  35510. nodeBuilder.vertexShader,
  35511. nodeBuilder.fragmentShader,
  35512. nodeBuilder.computeShader,
  35513. nodeBuilder.getAttributesArray(),
  35514. nodeBuilder.getBindings(),
  35515. nodeBuilder.updateNodes,
  35516. nodeBuilder.updateBeforeNodes,
  35517. nodeBuilder.updateAfterNodes,
  35518. nodeBuilder.observer,
  35519. nodeBuilder.transforms
  35520. );
  35521. }
  35522. /**
  35523. * Returns an environment node for the current configured
  35524. * scene environment.
  35525. *
  35526. * @param {Scene} scene - The scene.
  35527. * @return {Node} A node representing the current scene environment.
  35528. */
  35529. getEnvironmentNode( scene ) {
  35530. this.updateEnvironment( scene );
  35531. let environmentNode = null;
  35532. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  35533. environmentNode = scene.environmentNode;
  35534. } else {
  35535. const sceneData = this.get( scene );
  35536. if ( sceneData.environmentNode ) {
  35537. environmentNode = sceneData.environmentNode;
  35538. }
  35539. }
  35540. return environmentNode;
  35541. }
  35542. /**
  35543. * Returns a background node for the current configured
  35544. * scene background.
  35545. *
  35546. * @param {Scene} scene - The scene.
  35547. * @return {Node} A node representing the current scene background.
  35548. */
  35549. getBackgroundNode( scene ) {
  35550. this.updateBackground( scene );
  35551. let backgroundNode = null;
  35552. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  35553. backgroundNode = scene.backgroundNode;
  35554. } else {
  35555. const sceneData = this.get( scene );
  35556. if ( sceneData.backgroundNode ) {
  35557. backgroundNode = sceneData.backgroundNode;
  35558. }
  35559. }
  35560. return backgroundNode;
  35561. }
  35562. /**
  35563. * Returns a fog node for the current configured scene fog.
  35564. *
  35565. * @param {Scene} scene - The scene.
  35566. * @return {Node} A node representing the current scene fog.
  35567. */
  35568. getFogNode( scene ) {
  35569. this.updateFog( scene );
  35570. return scene.fogNode || this.get( scene ).fogNode || null;
  35571. }
  35572. /**
  35573. * Returns a cache key for the given scene and lights node.
  35574. * This key is used by `RenderObject` as a part of the dynamic
  35575. * cache key (a key that must be checked every time the render
  35576. * objects is drawn).
  35577. *
  35578. * @param {Scene} scene - The scene.
  35579. * @param {LightsNode} lightsNode - The lights node.
  35580. * @return {number} The cache key.
  35581. */
  35582. getCacheKey( scene, lightsNode ) {
  35583. _chainKeys$2[ 0 ] = scene;
  35584. _chainKeys$2[ 1 ] = lightsNode;
  35585. const callId = this.renderer.info.calls;
  35586. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  35587. if ( cacheKeyData.callId !== callId ) {
  35588. const environmentNode = this.getEnvironmentNode( scene );
  35589. const fogNode = this.getFogNode( scene );
  35590. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  35591. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  35592. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  35593. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  35594. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  35595. cacheKeyData.callId = callId;
  35596. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  35597. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  35598. _cacheKeyValues.length = 0;
  35599. }
  35600. _chainKeys$2.length = 0;
  35601. return cacheKeyData.cacheKey;
  35602. }
  35603. /**
  35604. * A boolean that indicates whether tone mapping should be enabled
  35605. * or not.
  35606. *
  35607. * @type {boolean}
  35608. */
  35609. get isToneMappingState() {
  35610. return this.renderer.getRenderTarget() ? false : true;
  35611. }
  35612. /**
  35613. * If a scene background is configured, this method makes sure to
  35614. * represent the background with a corresponding node-based implementation.
  35615. *
  35616. * @param {Scene} scene - The scene.
  35617. */
  35618. updateBackground( scene ) {
  35619. const sceneData = this.get( scene );
  35620. const background = scene.background;
  35621. if ( background ) {
  35622. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  35623. if ( sceneData.background !== background || forceUpdate ) {
  35624. const backgroundNode = this.getCacheNode( 'background', background, () => {
  35625. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  35626. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  35627. return pmremTexture( background );
  35628. } else {
  35629. let envMap;
  35630. if ( background.isCubeTexture === true ) {
  35631. envMap = cubeTexture( background );
  35632. } else {
  35633. envMap = texture( background );
  35634. }
  35635. return cubeMapNode( envMap );
  35636. }
  35637. } else if ( background.isTexture === true ) {
  35638. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  35639. } else if ( background.isColor !== true ) {
  35640. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  35641. }
  35642. }, forceUpdate );
  35643. sceneData.backgroundNode = backgroundNode;
  35644. sceneData.background = background;
  35645. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  35646. }
  35647. } else if ( sceneData.backgroundNode ) {
  35648. delete sceneData.backgroundNode;
  35649. delete sceneData.background;
  35650. }
  35651. }
  35652. /**
  35653. * This method is part of the caching of nodes which are used to represents the
  35654. * scene's background, fog or environment.
  35655. *
  35656. * @param {string} type - The type of object to cache.
  35657. * @param {Object} object - The object.
  35658. * @param {Function} callback - A callback that produces a node representation for the given object.
  35659. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  35660. * @return {Node} The node representation.
  35661. */
  35662. getCacheNode( type, object, callback, forceUpdate = false ) {
  35663. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  35664. let node = nodeCache.get( object );
  35665. if ( node === undefined || forceUpdate ) {
  35666. node = callback();
  35667. nodeCache.set( object, node );
  35668. }
  35669. return node;
  35670. }
  35671. /**
  35672. * If a scene fog is configured, this method makes sure to
  35673. * represent the fog with a corresponding node-based implementation.
  35674. *
  35675. * @param {Scene} scene - The scene.
  35676. */
  35677. updateFog( scene ) {
  35678. const sceneData = this.get( scene );
  35679. const sceneFog = scene.fog;
  35680. if ( sceneFog ) {
  35681. if ( sceneData.fog !== sceneFog ) {
  35682. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  35683. if ( sceneFog.isFogExp2 ) {
  35684. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  35685. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  35686. return fog( color, densityFogFactor( density ) );
  35687. } else if ( sceneFog.isFog ) {
  35688. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  35689. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  35690. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  35691. return fog( color, rangeFogFactor( near, far ) );
  35692. } else {
  35693. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  35694. }
  35695. } );
  35696. sceneData.fogNode = fogNode;
  35697. sceneData.fog = sceneFog;
  35698. }
  35699. } else {
  35700. delete sceneData.fogNode;
  35701. delete sceneData.fog;
  35702. }
  35703. }
  35704. /**
  35705. * If a scene environment is configured, this method makes sure to
  35706. * represent the environment with a corresponding node-based implementation.
  35707. *
  35708. * @param {Scene} scene - The scene.
  35709. */
  35710. updateEnvironment( scene ) {
  35711. const sceneData = this.get( scene );
  35712. const environment = scene.environment;
  35713. if ( environment ) {
  35714. if ( sceneData.environment !== environment ) {
  35715. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  35716. if ( environment.isCubeTexture === true ) {
  35717. return cubeTexture( environment );
  35718. } else if ( environment.isTexture === true ) {
  35719. return texture( environment );
  35720. } else {
  35721. console.error( 'Nodes: Unsupported environment configuration.', environment );
  35722. }
  35723. } );
  35724. sceneData.environmentNode = environmentNode;
  35725. sceneData.environment = environment;
  35726. }
  35727. } else if ( sceneData.environmentNode ) {
  35728. delete sceneData.environmentNode;
  35729. delete sceneData.environment;
  35730. }
  35731. }
  35732. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  35733. const nodeFrame = this.nodeFrame;
  35734. nodeFrame.renderer = renderer;
  35735. nodeFrame.scene = scene;
  35736. nodeFrame.object = object;
  35737. nodeFrame.camera = camera;
  35738. nodeFrame.material = material;
  35739. return nodeFrame;
  35740. }
  35741. getNodeFrameForRender( renderObject ) {
  35742. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  35743. }
  35744. /**
  35745. * Returns the current output cache key.
  35746. *
  35747. * @return {string} The output cache key.
  35748. */
  35749. getOutputCacheKey() {
  35750. const renderer = this.renderer;
  35751. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  35752. }
  35753. /**
  35754. * Checks if the output configuration (tone mapping and color space) for
  35755. * the given target has changed.
  35756. *
  35757. * @param {Texture} outputTarget - The output target.
  35758. * @return {boolean} Whether the output configuration has changed or not.
  35759. */
  35760. hasOutputChange( outputTarget ) {
  35761. const cacheKey = _outputNodeMap.get( outputTarget );
  35762. return cacheKey !== this.getOutputCacheKey();
  35763. }
  35764. /**
  35765. * Returns a node that represents the output configuration (tone mapping and
  35766. * color space) for the current target.
  35767. *
  35768. * @param {Texture} outputTarget - The output target.
  35769. * @return {Node} The output node.
  35770. */
  35771. getOutputNode( outputTarget ) {
  35772. const renderer = this.renderer;
  35773. const cacheKey = this.getOutputCacheKey();
  35774. const output = outputTarget.isArrayTexture ?
  35775. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  35776. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  35777. _outputNodeMap.set( outputTarget, cacheKey );
  35778. return output;
  35779. }
  35780. /**
  35781. * Triggers the call of `updateBefore()` methods
  35782. * for all nodes of the given render object.
  35783. *
  35784. * @param {RenderObject} renderObject - The render object.
  35785. */
  35786. updateBefore( renderObject ) {
  35787. const nodeBuilder = renderObject.getNodeBuilderState();
  35788. for ( const node of nodeBuilder.updateBeforeNodes ) {
  35789. // update frame state for each node
  35790. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  35791. }
  35792. }
  35793. /**
  35794. * Triggers the call of `updateAfter()` methods
  35795. * for all nodes of the given render object.
  35796. *
  35797. * @param {RenderObject} renderObject - The render object.
  35798. */
  35799. updateAfter( renderObject ) {
  35800. const nodeBuilder = renderObject.getNodeBuilderState();
  35801. for ( const node of nodeBuilder.updateAfterNodes ) {
  35802. // update frame state for each node
  35803. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  35804. }
  35805. }
  35806. /**
  35807. * Triggers the call of `update()` methods
  35808. * for all nodes of the given compute node.
  35809. *
  35810. * @param {Node} computeNode - The compute node.
  35811. */
  35812. updateForCompute( computeNode ) {
  35813. const nodeFrame = this.getNodeFrame();
  35814. const nodeBuilder = this.getForCompute( computeNode );
  35815. for ( const node of nodeBuilder.updateNodes ) {
  35816. nodeFrame.updateNode( node );
  35817. }
  35818. }
  35819. /**
  35820. * Triggers the call of `update()` methods
  35821. * for all nodes of the given compute node.
  35822. *
  35823. * @param {RenderObject} renderObject - The render object.
  35824. */
  35825. updateForRender( renderObject ) {
  35826. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35827. const nodeBuilder = renderObject.getNodeBuilderState();
  35828. for ( const node of nodeBuilder.updateNodes ) {
  35829. nodeFrame.updateNode( node );
  35830. }
  35831. }
  35832. /**
  35833. * Returns `true` if the given render object requires a refresh.
  35834. *
  35835. * @param {RenderObject} renderObject - The render object.
  35836. * @return {boolean} Whether the given render object requires a refresh or not.
  35837. */
  35838. needsRefresh( renderObject ) {
  35839. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35840. const monitor = renderObject.getMonitor();
  35841. return monitor.needsRefresh( renderObject, nodeFrame );
  35842. }
  35843. /**
  35844. * Frees the internal resources.
  35845. */
  35846. dispose() {
  35847. super.dispose();
  35848. this.nodeFrame = new NodeFrame();
  35849. this.nodeBuilderCache = new Map();
  35850. this.cacheLib = {};
  35851. }
  35852. }
  35853. const _plane = /*@__PURE__*/ new Plane();
  35854. /**
  35855. * Represents the state that is used to perform clipping via clipping planes.
  35856. * There is a default clipping context for each render context. When the
  35857. * scene holds instances of `ClippingGroup`, there will be a context for each
  35858. * group.
  35859. *
  35860. * @private
  35861. */
  35862. class ClippingContext {
  35863. /**
  35864. * Constructs a new clipping context.
  35865. *
  35866. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  35867. */
  35868. constructor( parentContext = null ) {
  35869. /**
  35870. * The clipping context's version.
  35871. *
  35872. * @type {number}
  35873. * @readonly
  35874. */
  35875. this.version = 0;
  35876. /**
  35877. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  35878. *
  35879. * @type {?boolean}
  35880. * @default null
  35881. */
  35882. this.clipIntersection = null;
  35883. /**
  35884. * The clipping context's cache key.
  35885. *
  35886. * @type {string}
  35887. */
  35888. this.cacheKey = '';
  35889. /**
  35890. * Whether the shadow pass is active or not.
  35891. *
  35892. * @type {boolean}
  35893. * @default false
  35894. */
  35895. this.shadowPass = false;
  35896. /**
  35897. * The view normal matrix.
  35898. *
  35899. * @type {Matrix3}
  35900. */
  35901. this.viewNormalMatrix = new Matrix3();
  35902. /**
  35903. * Internal cache for maintaining clipping contexts.
  35904. *
  35905. * @type {WeakMap<ClippingGroup,ClippingContext>}
  35906. */
  35907. this.clippingGroupContexts = new WeakMap();
  35908. /**
  35909. * The intersection planes.
  35910. *
  35911. * @type {Array<Vector4>}
  35912. */
  35913. this.intersectionPlanes = [];
  35914. /**
  35915. * The intersection planes.
  35916. *
  35917. * @type {Array<Vector4>}
  35918. */
  35919. this.unionPlanes = [];
  35920. /**
  35921. * The version of the clipping context's parent context.
  35922. *
  35923. * @type {?number}
  35924. * @readonly
  35925. */
  35926. this.parentVersion = null;
  35927. if ( parentContext !== null ) {
  35928. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  35929. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  35930. this.shadowPass = parentContext.shadowPass;
  35931. this.viewMatrix = parentContext.viewMatrix;
  35932. }
  35933. }
  35934. /**
  35935. * Projects the given source clipping planes and writes the result into the
  35936. * destination array.
  35937. *
  35938. * @param {Array<Plane>} source - The source clipping planes.
  35939. * @param {Array<Vector4>} destination - The destination.
  35940. * @param {number} offset - The offset.
  35941. */
  35942. projectPlanes( source, destination, offset ) {
  35943. const l = source.length;
  35944. for ( let i = 0; i < l; i ++ ) {
  35945. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  35946. const v = destination[ offset + i ];
  35947. const normal = _plane.normal;
  35948. v.x = - normal.x;
  35949. v.y = - normal.y;
  35950. v.z = - normal.z;
  35951. v.w = _plane.constant;
  35952. }
  35953. }
  35954. /**
  35955. * Updates the root clipping context of a scene.
  35956. *
  35957. * @param {Scene} scene - The scene.
  35958. * @param {Camera} camera - The camera that is used to render the scene.
  35959. */
  35960. updateGlobal( scene, camera ) {
  35961. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  35962. this.viewMatrix = camera.matrixWorldInverse;
  35963. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  35964. }
  35965. /**
  35966. * Updates the clipping context.
  35967. *
  35968. * @param {ClippingContext} parentContext - The parent context.
  35969. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  35970. */
  35971. update( parentContext, clippingGroup ) {
  35972. let update = false;
  35973. if ( parentContext.version !== this.parentVersion ) {
  35974. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  35975. this.unionPlanes = Array.from( parentContext.unionPlanes );
  35976. this.parentVersion = parentContext.version;
  35977. }
  35978. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  35979. this.clipIntersection = clippingGroup.clipIntersection;
  35980. if ( this.clipIntersection ) {
  35981. this.unionPlanes.length = parentContext.unionPlanes.length;
  35982. } else {
  35983. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  35984. }
  35985. }
  35986. const srcClippingPlanes = clippingGroup.clippingPlanes;
  35987. const l = srcClippingPlanes.length;
  35988. let dstClippingPlanes;
  35989. let offset;
  35990. if ( this.clipIntersection ) {
  35991. dstClippingPlanes = this.intersectionPlanes;
  35992. offset = parentContext.intersectionPlanes.length;
  35993. } else {
  35994. dstClippingPlanes = this.unionPlanes;
  35995. offset = parentContext.unionPlanes.length;
  35996. }
  35997. if ( dstClippingPlanes.length !== offset + l ) {
  35998. dstClippingPlanes.length = offset + l;
  35999. for ( let i = 0; i < l; i ++ ) {
  36000. dstClippingPlanes[ offset + i ] = new Vector4();
  36001. }
  36002. update = true;
  36003. }
  36004. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  36005. if ( update ) {
  36006. this.version ++;
  36007. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  36008. }
  36009. }
  36010. /**
  36011. * Returns a clipping context for the given clipping group.
  36012. *
  36013. * @param {ClippingGroup} clippingGroup - The clipping group.
  36014. * @return {ClippingContext} The clipping context.
  36015. */
  36016. getGroupContext( clippingGroup ) {
  36017. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  36018. let context = this.clippingGroupContexts.get( clippingGroup );
  36019. if ( context === undefined ) {
  36020. context = new ClippingContext( this );
  36021. this.clippingGroupContexts.set( clippingGroup, context );
  36022. }
  36023. context.update( this, clippingGroup );
  36024. return context;
  36025. }
  36026. /**
  36027. * The count of union clipping planes.
  36028. *
  36029. * @type {number}
  36030. * @readonly
  36031. */
  36032. get unionClippingCount() {
  36033. return this.unionPlanes.length;
  36034. }
  36035. }
  36036. /**
  36037. * This module is used to represent render bundles inside the renderer
  36038. * for further processing.
  36039. *
  36040. * @private
  36041. */
  36042. class RenderBundle {
  36043. /**
  36044. * Constructs a new bundle group.
  36045. *
  36046. * @param {BundleGroup} bundleGroup - The bundle group.
  36047. * @param {Camera} camera - The camera the bundle group is rendered with.
  36048. */
  36049. constructor( bundleGroup, camera ) {
  36050. this.bundleGroup = bundleGroup;
  36051. this.camera = camera;
  36052. }
  36053. }
  36054. const _chainKeys$1 = [];
  36055. /**
  36056. * This renderer module manages render bundles.
  36057. *
  36058. * @private
  36059. */
  36060. class RenderBundles {
  36061. /**
  36062. * Constructs a new render bundle management component.
  36063. */
  36064. constructor() {
  36065. /**
  36066. * A chain map for maintaining the render bundles.
  36067. *
  36068. * @type {ChainMap}
  36069. */
  36070. this.bundles = new ChainMap();
  36071. }
  36072. /**
  36073. * Returns a render bundle for the given bundle group and camera.
  36074. *
  36075. * @param {BundleGroup} bundleGroup - The bundle group.
  36076. * @param {Camera} camera - The camera the bundle group is rendered with.
  36077. * @return {RenderBundle} The render bundle.
  36078. */
  36079. get( bundleGroup, camera ) {
  36080. const bundles = this.bundles;
  36081. _chainKeys$1[ 0 ] = bundleGroup;
  36082. _chainKeys$1[ 1 ] = camera;
  36083. let bundle = bundles.get( _chainKeys$1 );
  36084. if ( bundle === undefined ) {
  36085. bundle = new RenderBundle( bundleGroup, camera );
  36086. bundles.set( _chainKeys$1, bundle );
  36087. }
  36088. _chainKeys$1.length = 0;
  36089. return bundle;
  36090. }
  36091. /**
  36092. * Frees all internal resources.
  36093. */
  36094. dispose() {
  36095. this.bundles = new ChainMap();
  36096. }
  36097. }
  36098. /**
  36099. * The purpose of a node library is to assign node implementations
  36100. * to existing library features. In `WebGPURenderer` lights, materials
  36101. * which are not based on `NodeMaterial` as well as tone mapping techniques
  36102. * are implemented with node-based modules.
  36103. *
  36104. * @private
  36105. */
  36106. class NodeLibrary {
  36107. /**
  36108. * Constructs a new node library.
  36109. */
  36110. constructor() {
  36111. /**
  36112. * A weak map that maps lights to light nodes.
  36113. *
  36114. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  36115. */
  36116. this.lightNodes = new WeakMap();
  36117. /**
  36118. * A map that maps materials to node materials.
  36119. *
  36120. * @type {Map<string,NodeMaterial.constructor>}
  36121. */
  36122. this.materialNodes = new Map();
  36123. /**
  36124. * A map that maps tone mapping techniques (constants)
  36125. * to tone mapping node functions.
  36126. *
  36127. * @type {Map<number,Function>}
  36128. */
  36129. this.toneMappingNodes = new Map();
  36130. }
  36131. /**
  36132. * Returns a matching node material instance for the given material object.
  36133. *
  36134. * This method also assigns/copies the properties of the given material object
  36135. * to the node material. This is done to make sure the current material
  36136. * configuration carries over to the node version.
  36137. *
  36138. * @param {Material} material - A material.
  36139. * @return {NodeMaterial} The corresponding node material.
  36140. */
  36141. fromMaterial( material ) {
  36142. if ( material.isNodeMaterial ) return material;
  36143. let nodeMaterial = null;
  36144. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  36145. if ( nodeMaterialClass !== null ) {
  36146. nodeMaterial = new nodeMaterialClass();
  36147. for ( const key in material ) {
  36148. nodeMaterial[ key ] = material[ key ];
  36149. }
  36150. }
  36151. return nodeMaterial;
  36152. }
  36153. /**
  36154. * Adds a tone mapping node function for a tone mapping technique (constant).
  36155. *
  36156. * @param {Function} toneMappingNode - The tone mapping node function.
  36157. * @param {number} toneMapping - The tone mapping.
  36158. */
  36159. addToneMapping( toneMappingNode, toneMapping ) {
  36160. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  36161. }
  36162. /**
  36163. * Returns a tone mapping node function for a tone mapping technique (constant).
  36164. *
  36165. * @param {number} toneMapping - The tone mapping.
  36166. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  36167. */
  36168. getToneMappingFunction( toneMapping ) {
  36169. return this.toneMappingNodes.get( toneMapping ) || null;
  36170. }
  36171. /**
  36172. * Returns a node material class definition for a material type.
  36173. *
  36174. * @param {string} materialType - The material type.
  36175. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  36176. */
  36177. getMaterialNodeClass( materialType ) {
  36178. return this.materialNodes.get( materialType ) || null;
  36179. }
  36180. /**
  36181. * Adds a node material class definition for a given material type.
  36182. *
  36183. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  36184. * @param {string} materialClassType - The material type.
  36185. */
  36186. addMaterial( materialNodeClass, materialClassType ) {
  36187. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  36188. }
  36189. /**
  36190. * Returns a light node class definition for a light class definition.
  36191. *
  36192. * @param {Light.constructor} light - The light class definition.
  36193. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  36194. */
  36195. getLightNodeClass( light ) {
  36196. return this.lightNodes.get( light ) || null;
  36197. }
  36198. /**
  36199. * Adds a light node class definition for a given light class definition.
  36200. *
  36201. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  36202. * @param {Light.constructor} lightClass - The light class definition.
  36203. */
  36204. addLight( lightNodeClass, lightClass ) {
  36205. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  36206. }
  36207. /**
  36208. * Adds a node class definition for the given type to the provided type library.
  36209. *
  36210. * @param {any} nodeClass - The node class definition.
  36211. * @param {number|string} type - The object type.
  36212. * @param {Map} library - The type library.
  36213. */
  36214. addType( nodeClass, type, library ) {
  36215. if ( library.has( type ) ) {
  36216. console.warn( `Redefinition of node ${ type }` );
  36217. return;
  36218. }
  36219. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  36220. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  36221. library.set( type, nodeClass );
  36222. }
  36223. /**
  36224. * Adds a node class definition for the given class definition to the provided type library.
  36225. *
  36226. * @param {any} nodeClass - The node class definition.
  36227. * @param {any} baseClass - The class definition.
  36228. * @param {WeakMap} library - The type library.
  36229. */
  36230. addClass( nodeClass, baseClass, library ) {
  36231. if ( library.has( baseClass ) ) {
  36232. console.warn( `Redefinition of node ${ baseClass.name }` );
  36233. return;
  36234. }
  36235. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  36236. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  36237. library.set( baseClass, nodeClass );
  36238. }
  36239. }
  36240. const _defaultLights = /*@__PURE__*/ new LightsNode();
  36241. const _chainKeys = [];
  36242. /**
  36243. * This renderer module manages the lights nodes which are unique
  36244. * per scene and camera combination.
  36245. *
  36246. * The lights node itself is later configured in the render list
  36247. * with the actual lights from the scene.
  36248. *
  36249. * @private
  36250. * @augments ChainMap
  36251. */
  36252. class Lighting extends ChainMap {
  36253. /**
  36254. * Constructs a lighting management component.
  36255. */
  36256. constructor() {
  36257. super();
  36258. }
  36259. /**
  36260. * Creates a new lights node for the given array of lights.
  36261. *
  36262. * @param {Array<Light>} lights - The render object.
  36263. * @return {LightsNode} The lights node.
  36264. */
  36265. createNode( lights = [] ) {
  36266. return new LightsNode().setLights( lights );
  36267. }
  36268. /**
  36269. * Returns a lights node for the given scene and camera.
  36270. *
  36271. * @param {Scene} scene - The scene.
  36272. * @param {Camera} camera - The camera.
  36273. * @return {LightsNode} The lights node.
  36274. */
  36275. getNode( scene, camera ) {
  36276. // ignore post-processing
  36277. if ( scene.isQuadMesh ) return _defaultLights;
  36278. _chainKeys[ 0 ] = scene;
  36279. _chainKeys[ 1 ] = camera;
  36280. let node = this.get( _chainKeys );
  36281. if ( node === undefined ) {
  36282. node = this.createNode();
  36283. this.set( _chainKeys, node );
  36284. }
  36285. _chainKeys.length = 0;
  36286. return node;
  36287. }
  36288. }
  36289. /**
  36290. * A special type of render target that is used when rendering
  36291. * with the WebXR Device API.
  36292. *
  36293. * @private
  36294. * @augments RenderTarget
  36295. */
  36296. class XRRenderTarget extends RenderTarget {
  36297. /**
  36298. * Constructs a new XR render target.
  36299. *
  36300. * @param {number} [width=1] - The width of the render target.
  36301. * @param {number} [height=1] - The height of the render target.
  36302. * @param {Object} [options={}] - The configuration options.
  36303. */
  36304. constructor( width = 1, height = 1, options = {} ) {
  36305. super( width, height, options );
  36306. /**
  36307. * This flag can be used for type testing.
  36308. *
  36309. * @type {boolean}
  36310. * @readonly
  36311. * @default true
  36312. */
  36313. this.isXRRenderTarget = true;
  36314. /**
  36315. * Whether the attachments of the render target
  36316. * are defined by external textures. This flag is
  36317. * set to `true` when using the WebXR Layers API.
  36318. *
  36319. * @private
  36320. * @type {boolean}
  36321. * @default false
  36322. */
  36323. this._hasExternalTextures = false;
  36324. /**
  36325. * Whether a depth buffer should automatically be allocated
  36326. * for this XR render target or not.
  36327. *
  36328. * Allocating a depth buffer is the default behavior of XR render
  36329. * targets. However, when using the WebXR Layers API, this flag
  36330. * must be set to `false` when the `ignoreDepthValues` property of
  36331. * the projection layers evaluates to `false`.
  36332. *
  36333. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  36334. *
  36335. * @private
  36336. * @type {boolean}
  36337. * @default true
  36338. */
  36339. this._autoAllocateDepthBuffer = true;
  36340. /**
  36341. * Whether this render target is associated with a XRWebGLLayer.
  36342. *
  36343. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  36344. * this means that you don't have access to its bound color,
  36345. * stencil and depth buffers. We need to handle this framebuffer
  36346. * differently since its textures are always bound.
  36347. *
  36348. * @private
  36349. * @type {boolean}
  36350. * @default false
  36351. * */
  36352. this._isOpaqueFramebuffer = false;
  36353. }
  36354. copy( source ) {
  36355. super.copy( source );
  36356. this._hasExternalTextures = source._hasExternalTextures;
  36357. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  36358. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  36359. return this;
  36360. }
  36361. }
  36362. const _cameraLPos = /*@__PURE__*/ new Vector3();
  36363. const _cameraRPos = /*@__PURE__*/ new Vector3();
  36364. /**
  36365. * The XR manager is built on top of the WebXR Device API to
  36366. * manage XR sessions with `WebGPURenderer`.
  36367. *
  36368. * XR is currently only supported with a WebGL 2 backend.
  36369. *
  36370. * @augments EventDispatcher
  36371. */
  36372. class XRManager extends EventDispatcher {
  36373. /**
  36374. * Constructs a new XR manager.
  36375. *
  36376. * @param {Renderer} renderer - The renderer.
  36377. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  36378. */
  36379. constructor( renderer, multiview = false ) {
  36380. super();
  36381. /**
  36382. * This flag globally enables XR rendering.
  36383. *
  36384. * @type {boolean}
  36385. * @default false
  36386. */
  36387. this.enabled = false;
  36388. /**
  36389. * Whether the XR device is currently presenting or not.
  36390. *
  36391. * @type {boolean}
  36392. * @default false
  36393. * @readonly
  36394. */
  36395. this.isPresenting = false;
  36396. /**
  36397. * Whether the XR camera should automatically be updated or not.
  36398. *
  36399. * @type {boolean}
  36400. * @default true
  36401. */
  36402. this.cameraAutoUpdate = true;
  36403. /**
  36404. * The renderer.
  36405. *
  36406. * @private
  36407. * @type {Renderer}
  36408. */
  36409. this._renderer = renderer;
  36410. // camera
  36411. /**
  36412. * Represents the camera for the left eye.
  36413. *
  36414. * @private
  36415. * @type {PerspectiveCamera}
  36416. */
  36417. this._cameraL = new PerspectiveCamera();
  36418. this._cameraL.viewport = new Vector4();
  36419. /**
  36420. * Represents the camera for the right eye.
  36421. *
  36422. * @private
  36423. * @type {PerspectiveCamera}
  36424. */
  36425. this._cameraR = new PerspectiveCamera();
  36426. this._cameraR.viewport = new Vector4();
  36427. /**
  36428. * A list of cameras used for rendering the XR views.
  36429. *
  36430. * @private
  36431. * @type {Array<Camera>}
  36432. */
  36433. this._cameras = [ this._cameraL, this._cameraR ];
  36434. /**
  36435. * The main XR camera.
  36436. *
  36437. * @private
  36438. * @type {ArrayCamera}
  36439. */
  36440. this._cameraXR = new ArrayCamera();
  36441. /**
  36442. * The current near value of the XR camera.
  36443. *
  36444. * @private
  36445. * @type {?number}
  36446. * @default null
  36447. */
  36448. this._currentDepthNear = null;
  36449. /**
  36450. * The current far value of the XR camera.
  36451. *
  36452. * @private
  36453. * @type {?number}
  36454. * @default null
  36455. */
  36456. this._currentDepthFar = null;
  36457. /**
  36458. * A list of WebXR controllers requested by the application.
  36459. *
  36460. * @private
  36461. * @type {Array<WebXRController>}
  36462. */
  36463. this._controllers = [];
  36464. /**
  36465. * A list of XR input source. Each input source belongs to
  36466. * an instance of WebXRController.
  36467. *
  36468. * @private
  36469. * @type {Array<XRInputSource?>}
  36470. */
  36471. this._controllerInputSources = [];
  36472. /**
  36473. * The XR render target that represents the rendering destination
  36474. * during an active XR session.
  36475. *
  36476. * @private
  36477. * @type {?RenderTarget}
  36478. * @default null
  36479. */
  36480. this._xrRenderTarget = null;
  36481. /**
  36482. * An array holding all the non-projection layers
  36483. *
  36484. * @private
  36485. * @type {Array<Object>}
  36486. * @default []
  36487. */
  36488. this._layers = [];
  36489. /**
  36490. * Whether the device has support for all layer types.
  36491. *
  36492. * @type {boolean}
  36493. * @default false
  36494. */
  36495. this._supportsLayers = false;
  36496. /**
  36497. * Whether the device supports binding gl objects.
  36498. *
  36499. * @private
  36500. * @type {boolean}
  36501. * @readonly
  36502. */
  36503. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  36504. this._frameBufferTargets = null;
  36505. /**
  36506. * Helper function to create native WebXR Layer.
  36507. *
  36508. * @private
  36509. * @type {Function}
  36510. */
  36511. this._createXRLayer = createXRLayer.bind( this );
  36512. /**
  36513. * The current WebGL context.
  36514. *
  36515. * @private
  36516. * @type {?WebGL2RenderingContext}
  36517. * @default null
  36518. */
  36519. this._gl = null;
  36520. /**
  36521. * The current animation context.
  36522. *
  36523. * @private
  36524. * @type {?Window}
  36525. * @default null
  36526. */
  36527. this._currentAnimationContext = null;
  36528. /**
  36529. * The current animation loop.
  36530. *
  36531. * @private
  36532. * @type {?Function}
  36533. * @default null
  36534. */
  36535. this._currentAnimationLoop = null;
  36536. /**
  36537. * The current pixel ratio.
  36538. *
  36539. * @private
  36540. * @type {?number}
  36541. * @default null
  36542. */
  36543. this._currentPixelRatio = null;
  36544. /**
  36545. * The current size of the renderer's canvas
  36546. * in logical pixel unit.
  36547. *
  36548. * @private
  36549. * @type {Vector2}
  36550. */
  36551. this._currentSize = new Vector2();
  36552. /**
  36553. * The default event listener for handling events inside a XR session.
  36554. *
  36555. * @private
  36556. * @type {Function}
  36557. */
  36558. this._onSessionEvent = onSessionEvent.bind( this );
  36559. /**
  36560. * The event listener for handling the end of a XR session.
  36561. *
  36562. * @private
  36563. * @type {Function}
  36564. */
  36565. this._onSessionEnd = onSessionEnd.bind( this );
  36566. /**
  36567. * The event listener for handling the `inputsourceschange` event.
  36568. *
  36569. * @private
  36570. * @type {Function}
  36571. */
  36572. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  36573. /**
  36574. * The animation loop which is used as a replacement for the default
  36575. * animation loop of the application. It is only used when a XR session
  36576. * is active.
  36577. *
  36578. * @private
  36579. * @type {Function}
  36580. */
  36581. this._onAnimationFrame = onAnimationFrame.bind( this );
  36582. /**
  36583. * The current XR reference space.
  36584. *
  36585. * @private
  36586. * @type {?XRReferenceSpace}
  36587. * @default null
  36588. */
  36589. this._referenceSpace = null;
  36590. /**
  36591. * The current XR reference space type.
  36592. *
  36593. * @private
  36594. * @type {XRReferenceSpaceType}
  36595. * @default 'local-floor'
  36596. */
  36597. this._referenceSpaceType = 'local-floor';
  36598. /**
  36599. * A custom reference space defined by the application.
  36600. *
  36601. * @private
  36602. * @type {?XRReferenceSpace}
  36603. * @default null
  36604. */
  36605. this._customReferenceSpace = null;
  36606. /**
  36607. * The framebuffer scale factor.
  36608. *
  36609. * @private
  36610. * @type {number}
  36611. * @default 1
  36612. */
  36613. this._framebufferScaleFactor = 1;
  36614. /**
  36615. * The foveation factor.
  36616. *
  36617. * @private
  36618. * @type {number}
  36619. * @default 1
  36620. */
  36621. this._foveation = 1.0;
  36622. /**
  36623. * A reference to the current XR session.
  36624. *
  36625. * @private
  36626. * @type {?XRSession}
  36627. * @default null
  36628. */
  36629. this._session = null;
  36630. /**
  36631. * A reference to the current XR base layer.
  36632. *
  36633. * @private
  36634. * @type {?XRWebGLLayer}
  36635. * @default null
  36636. */
  36637. this._glBaseLayer = null;
  36638. /**
  36639. * A reference to the current XR binding.
  36640. *
  36641. * @private
  36642. * @type {?XRWebGLBinding}
  36643. * @default null
  36644. */
  36645. this._glBinding = null;
  36646. /**
  36647. * A reference to the current XR projection layer.
  36648. *
  36649. * @private
  36650. * @type {?XRProjectionLayer}
  36651. * @default null
  36652. */
  36653. this._glProjLayer = null;
  36654. /**
  36655. * A reference to the current XR frame.
  36656. *
  36657. * @private
  36658. * @type {?XRFrame}
  36659. * @default null
  36660. */
  36661. this._xrFrame = null;
  36662. /**
  36663. * Whether to use the WebXR Layers API or not.
  36664. *
  36665. * @private
  36666. * @type {boolean}
  36667. * @readonly
  36668. */
  36669. this._useLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  36670. /**
  36671. * Whether the usage of multiview has been requested by the application or not.
  36672. *
  36673. * @private
  36674. * @type {boolean}
  36675. * @default false
  36676. * @readonly
  36677. */
  36678. this._useMultiviewIfPossible = multiview;
  36679. /**
  36680. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  36681. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  36682. *
  36683. * @private
  36684. * @type {boolean}
  36685. * @readonly
  36686. */
  36687. this._useMultiview = false;
  36688. }
  36689. /**
  36690. * Returns an instance of `THREE.Group` that represents the transformation
  36691. * of a XR controller in target ray space. The requested controller is defined
  36692. * by the given index.
  36693. *
  36694. * @param {number} index - The index of the XR controller.
  36695. * @return {Group} A group that represents the controller's transformation.
  36696. */
  36697. getController( index ) {
  36698. const controller = this._getController( index );
  36699. return controller.getTargetRaySpace();
  36700. }
  36701. /**
  36702. * Returns an instance of `THREE.Group` that represents the transformation
  36703. * of a XR controller in grip space. The requested controller is defined
  36704. * by the given index.
  36705. *
  36706. * @param {number} index - The index of the XR controller.
  36707. * @return {Group} A group that represents the controller's transformation.
  36708. */
  36709. getControllerGrip( index ) {
  36710. const controller = this._getController( index );
  36711. return controller.getGripSpace();
  36712. }
  36713. /**
  36714. * Returns an instance of `THREE.Group` that represents the transformation
  36715. * of a XR controller in hand space. The requested controller is defined
  36716. * by the given index.
  36717. *
  36718. * @param {number} index - The index of the XR controller.
  36719. * @return {Group} A group that represents the controller's transformation.
  36720. */
  36721. getHand( index ) {
  36722. const controller = this._getController( index );
  36723. return controller.getHandSpace();
  36724. }
  36725. /**
  36726. * Returns the foveation value.
  36727. *
  36728. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  36729. */
  36730. getFoveation() {
  36731. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  36732. return undefined;
  36733. }
  36734. return this._foveation;
  36735. }
  36736. /**
  36737. * Sets the foveation value.
  36738. *
  36739. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  36740. * and `1` means maximum foveation (the edges render at lower resolution).
  36741. */
  36742. setFoveation( foveation ) {
  36743. this._foveation = foveation;
  36744. if ( this._glProjLayer !== null ) {
  36745. this._glProjLayer.fixedFoveation = foveation;
  36746. }
  36747. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  36748. this._glBaseLayer.fixedFoveation = foveation;
  36749. }
  36750. }
  36751. /**
  36752. * Returns the framebuffer scale factor.
  36753. *
  36754. * @return {number} The framebuffer scale factor.
  36755. */
  36756. getFramebufferScaleFactor() {
  36757. return this._framebufferScaleFactor;
  36758. }
  36759. /**
  36760. * Sets the framebuffer scale factor.
  36761. *
  36762. * This method can not be used during a XR session.
  36763. *
  36764. * @param {number} factor - The framebuffer scale factor.
  36765. */
  36766. setFramebufferScaleFactor( factor ) {
  36767. this._framebufferScaleFactor = factor;
  36768. if ( this.isPresenting === true ) {
  36769. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  36770. }
  36771. }
  36772. /**
  36773. * Returns the reference space type.
  36774. *
  36775. * @return {XRReferenceSpaceType} The reference space type.
  36776. */
  36777. getReferenceSpaceType() {
  36778. return this._referenceSpaceType;
  36779. }
  36780. /**
  36781. * Sets the reference space type.
  36782. *
  36783. * This method can not be used during a XR session.
  36784. *
  36785. * @param {XRReferenceSpaceType} type - The reference space type.
  36786. */
  36787. setReferenceSpaceType( type ) {
  36788. this._referenceSpaceType = type;
  36789. if ( this.isPresenting === true ) {
  36790. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  36791. }
  36792. }
  36793. /**
  36794. * Returns the XR reference space.
  36795. *
  36796. * @return {XRReferenceSpace} The XR reference space.
  36797. */
  36798. getReferenceSpace() {
  36799. return this._customReferenceSpace || this._referenceSpace;
  36800. }
  36801. /**
  36802. * Sets a custom XR reference space.
  36803. *
  36804. * @param {XRReferenceSpace} space - The XR reference space.
  36805. */
  36806. setReferenceSpace( space ) {
  36807. this._customReferenceSpace = space;
  36808. }
  36809. /**
  36810. * Returns the XR camera.
  36811. *
  36812. * @return {ArrayCamera} The XR camera.
  36813. */
  36814. getCamera() {
  36815. return this._cameraXR;
  36816. }
  36817. /**
  36818. * Returns the environment blend mode from the current XR session.
  36819. *
  36820. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  36821. */
  36822. getEnvironmentBlendMode() {
  36823. if ( this._session !== null ) {
  36824. return this._session.environmentBlendMode;
  36825. }
  36826. }
  36827. /**
  36828. * Returns the current XR frame.
  36829. *
  36830. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  36831. */
  36832. getFrame() {
  36833. return this._xrFrame;
  36834. }
  36835. /**
  36836. * Returns `true` if the engine renders to a multiview target.
  36837. *
  36838. * @return {boolean} Whether the engine renders to a multiview render target or not.
  36839. */
  36840. useMultiview() {
  36841. return this._useMultiview;
  36842. }
  36843. /**
  36844. * This method can be used in XR applications to create a quadratic layer that presents a separate
  36845. * rendered scene.
  36846. *
  36847. * @param {number} width - The width of the layer plane in world units.
  36848. * @param {number} height - The height of the layer plane in world units.
  36849. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  36850. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  36851. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  36852. * @param {number} pixelheight - The height of the layer's render target in pixels.
  36853. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  36854. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  36855. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  36856. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  36857. */
  36858. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  36859. const geometry = new PlaneGeometry( width, height );
  36860. const renderTarget = new XRRenderTarget(
  36861. pixelwidth,
  36862. pixelheight,
  36863. {
  36864. format: RGBAFormat,
  36865. type: UnsignedByteType,
  36866. depthTexture: new DepthTexture(
  36867. pixelwidth,
  36868. pixelheight,
  36869. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  36870. undefined,
  36871. undefined,
  36872. undefined,
  36873. undefined,
  36874. undefined,
  36875. undefined,
  36876. attributes.stencil ? DepthStencilFormat : DepthFormat
  36877. ),
  36878. stencilBuffer: attributes.stencil,
  36879. resolveDepthBuffer: false,
  36880. resolveStencilBuffer: false
  36881. } );
  36882. renderTarget._autoAllocateDepthBuffer = true;
  36883. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  36884. material.map = renderTarget.texture;
  36885. material.map.offset.y = 1;
  36886. material.map.repeat.y = -1;
  36887. const plane = new Mesh( geometry, material );
  36888. plane.position.copy( translation );
  36889. plane.quaternion.copy( quaternion );
  36890. const layer = {
  36891. type: 'quad',
  36892. width: width,
  36893. height: height,
  36894. translation: translation,
  36895. quaternion: quaternion,
  36896. pixelwidth: pixelwidth,
  36897. pixelheight: pixelheight,
  36898. plane: plane,
  36899. material: material,
  36900. rendercall: rendercall,
  36901. renderTarget: renderTarget };
  36902. this._layers.push( layer );
  36903. if ( this._session !== null ) {
  36904. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  36905. layer.plane.material.blending = CustomBlending;
  36906. layer.plane.material.blendEquation = AddEquation;
  36907. layer.plane.material.blendSrc = ZeroFactor;
  36908. layer.plane.material.blendDst = ZeroFactor;
  36909. layer.xrlayer = this._createXRLayer( layer );
  36910. const xrlayers = this._session.renderState.layers;
  36911. xrlayers.unshift( layer.xrlayer );
  36912. this._session.updateRenderState( { layers: xrlayers } );
  36913. } else {
  36914. renderTarget.isXRRenderTarget = false;
  36915. }
  36916. return plane;
  36917. }
  36918. /**
  36919. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  36920. * rendered scene.
  36921. *
  36922. * @param {number} radius - The radius of the cylinder in world units.
  36923. * @param {number} centralAngle - The central angle of the cylinder in radians.
  36924. * @param {number} aspectratio - The aspect ratio.
  36925. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  36926. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  36927. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  36928. * @param {number} pixelheight - The height of the layer's render target in pixels.
  36929. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  36930. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  36931. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  36932. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  36933. */
  36934. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  36935. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  36936. const renderTarget = new XRRenderTarget(
  36937. pixelwidth,
  36938. pixelheight,
  36939. {
  36940. format: RGBAFormat,
  36941. type: UnsignedByteType,
  36942. depthTexture: new DepthTexture(
  36943. pixelwidth,
  36944. pixelheight,
  36945. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  36946. undefined,
  36947. undefined,
  36948. undefined,
  36949. undefined,
  36950. undefined,
  36951. undefined,
  36952. attributes.stencil ? DepthStencilFormat : DepthFormat
  36953. ),
  36954. stencilBuffer: attributes.stencil,
  36955. resolveDepthBuffer: false,
  36956. resolveStencilBuffer: false
  36957. } );
  36958. renderTarget._autoAllocateDepthBuffer = true;
  36959. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  36960. material.map = renderTarget.texture;
  36961. material.map.offset.y = 1;
  36962. material.map.repeat.y = -1;
  36963. const plane = new Mesh( geometry, material );
  36964. plane.position.copy( translation );
  36965. plane.quaternion.copy( quaternion );
  36966. const layer = {
  36967. type: 'cylinder',
  36968. radius: radius,
  36969. centralAngle: centralAngle,
  36970. aspectratio: aspectratio,
  36971. translation: translation,
  36972. quaternion: quaternion,
  36973. pixelwidth: pixelwidth,
  36974. pixelheight: pixelheight,
  36975. plane: plane,
  36976. material: material,
  36977. rendercall: rendercall,
  36978. renderTarget: renderTarget };
  36979. this._layers.push( layer );
  36980. if ( this._session !== null ) {
  36981. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  36982. layer.plane.material.blending = CustomBlending;
  36983. layer.plane.material.blendEquation = AddEquation;
  36984. layer.plane.material.blendSrc = ZeroFactor;
  36985. layer.plane.material.blendDst = ZeroFactor;
  36986. layer.xrlayer = this._createXRLayer( layer );
  36987. const xrlayers = this._session.renderState.layers;
  36988. xrlayers.unshift( layer.xrlayer );
  36989. this._session.updateRenderState( { layers: xrlayers } );
  36990. } else {
  36991. renderTarget.isXRRenderTarget = false;
  36992. }
  36993. return plane;
  36994. }
  36995. /**
  36996. * Renders the XR layers that have been previously added to the scene.
  36997. *
  36998. * This method is usually called in your animation loop before rendering
  36999. * the actual scene via `renderer.render( scene, camera );`.
  37000. */
  37001. renderLayers( ) {
  37002. const translationObject = new Vector3();
  37003. const quaternionObject = new Quaternion();
  37004. const renderer = this._renderer;
  37005. const wasPresenting = this.isPresenting;
  37006. const rendererOutputTarget = renderer.getOutputRenderTarget();
  37007. const rendererFramebufferTarget = renderer._frameBufferTarget;
  37008. this.isPresenting = false;
  37009. const rendererSize = new Vector2();
  37010. renderer.getSize( rendererSize );
  37011. const rendererQuad = renderer._quad;
  37012. for ( const layer of this._layers ) {
  37013. layer.renderTarget.isXRRenderTarget = this._session !== null;
  37014. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  37015. if ( layer.renderTarget.isXRRenderTarget && this._supportsLayers ) {
  37016. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  37017. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  37018. renderer.backend.setXRRenderTargetTextures(
  37019. layer.renderTarget,
  37020. glSubImage.colorTexture,
  37021. undefined );
  37022. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  37023. renderer.setOutputRenderTarget( layer.renderTarget );
  37024. renderer.setRenderTarget( null );
  37025. renderer._frameBufferTarget = null;
  37026. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  37027. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  37028. if ( ! frameBufferTarget ) {
  37029. renderer._quad = new QuadMesh( new NodeMaterial() );
  37030. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  37031. } else {
  37032. renderer._frameBufferTarget = frameBufferTarget;
  37033. renderer._quad = quad;
  37034. }
  37035. layer.rendercall();
  37036. renderer._frameBufferTarget = null;
  37037. } else {
  37038. renderer.setRenderTarget( layer.renderTarget );
  37039. layer.rendercall();
  37040. }
  37041. }
  37042. renderer.setRenderTarget( null );
  37043. renderer.setOutputRenderTarget( rendererOutputTarget );
  37044. renderer._frameBufferTarget = rendererFramebufferTarget;
  37045. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  37046. renderer._quad = rendererQuad;
  37047. this.isPresenting = wasPresenting;
  37048. }
  37049. /**
  37050. * Returns the current XR session.
  37051. *
  37052. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  37053. */
  37054. getSession() {
  37055. return this._session;
  37056. }
  37057. /**
  37058. * After a XR session has been requested usually with one of the `*Button` modules, it
  37059. * is injected into the renderer with this method. This method triggers the start of
  37060. * the actual XR rendering.
  37061. *
  37062. * @async
  37063. * @param {XRSession} session - The XR session to set.
  37064. * @return {Promise} A Promise that resolves when the session has been set.
  37065. */
  37066. async setSession( session ) {
  37067. const renderer = this._renderer;
  37068. const backend = renderer.backend;
  37069. this._gl = renderer.getContext();
  37070. const gl = this._gl;
  37071. const attributes = gl.getContextAttributes();
  37072. this._session = session;
  37073. if ( session !== null ) {
  37074. 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.' );
  37075. session.addEventListener( 'select', this._onSessionEvent );
  37076. session.addEventListener( 'selectstart', this._onSessionEvent );
  37077. session.addEventListener( 'selectend', this._onSessionEvent );
  37078. session.addEventListener( 'squeeze', this._onSessionEvent );
  37079. session.addEventListener( 'squeezestart', this._onSessionEvent );
  37080. session.addEventListener( 'squeezeend', this._onSessionEvent );
  37081. session.addEventListener( 'end', this._onSessionEnd );
  37082. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  37083. await backend.makeXRCompatible();
  37084. this._currentPixelRatio = renderer.getPixelRatio();
  37085. renderer.getSize( this._currentSize );
  37086. this._currentAnimationContext = renderer._animation.getContext();
  37087. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  37088. renderer._animation.stop();
  37089. //
  37090. if ( this._supportsGlBinding ) {
  37091. const glBinding = new XRWebGLBinding( session, gl );
  37092. this._glBinding = glBinding;
  37093. }
  37094. //
  37095. if ( this._useLayers === true ) {
  37096. // default path using XRProjectionLayer
  37097. let depthFormat = null;
  37098. let depthType = null;
  37099. let glDepthFormat = null;
  37100. if ( renderer.depth ) {
  37101. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  37102. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  37103. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  37104. }
  37105. const projectionlayerInit = {
  37106. colorFormat: gl.RGBA8,
  37107. depthFormat: glDepthFormat,
  37108. scaleFactor: this._framebufferScaleFactor,
  37109. clearOnAccess: false
  37110. };
  37111. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  37112. projectionlayerInit.textureType = 'texture-array';
  37113. this._useMultiview = true;
  37114. }
  37115. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  37116. const layersArray = [ glProjLayer ];
  37117. this._glProjLayer = glProjLayer;
  37118. renderer.setPixelRatio( 1 );
  37119. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  37120. const depth = this._useMultiview ? 2 : 1;
  37121. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  37122. this._xrRenderTarget = new XRRenderTarget(
  37123. glProjLayer.textureWidth,
  37124. glProjLayer.textureHeight,
  37125. {
  37126. format: RGBAFormat,
  37127. type: UnsignedByteType,
  37128. colorSpace: renderer.outputColorSpace,
  37129. depthTexture: depthTexture,
  37130. stencilBuffer: renderer.stencil,
  37131. samples: attributes.antialias ? 4 : 0,
  37132. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  37133. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  37134. depth: this._useMultiview ? 2 : 1,
  37135. multiview: this._useMultiview
  37136. } );
  37137. this._xrRenderTarget._hasExternalTextures = true;
  37138. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  37139. this._supportsLayers = session.enabledFeatures.includes( 'layers' );
  37140. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  37141. if ( this._supportsLayers ) {
  37142. // switch layers to native
  37143. for ( const layer of this._layers ) {
  37144. // change material so it "punches" out a hole to show the XR Layer.
  37145. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  37146. layer.plane.material.blending = CustomBlending;
  37147. layer.plane.material.blendEquation = AddEquation;
  37148. layer.plane.material.blendSrc = ZeroFactor;
  37149. layer.plane.material.blendDst = ZeroFactor;
  37150. layer.xrlayer = this._createXRLayer( layer );
  37151. layersArray.unshift( layer.xrlayer );
  37152. }
  37153. }
  37154. session.updateRenderState( { layers: layersArray } );
  37155. } else {
  37156. // fallback to XRWebGLLayer
  37157. const layerInit = {
  37158. antialias: renderer.samples > 0,
  37159. alpha: true,
  37160. depth: renderer.depth,
  37161. stencil: renderer.stencil,
  37162. framebufferScaleFactor: this.getFramebufferScaleFactor()
  37163. };
  37164. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  37165. this._glBaseLayer = glBaseLayer;
  37166. session.updateRenderState( { baseLayer: glBaseLayer } );
  37167. renderer.setPixelRatio( 1 );
  37168. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  37169. this._xrRenderTarget = new XRRenderTarget(
  37170. glBaseLayer.framebufferWidth,
  37171. glBaseLayer.framebufferHeight,
  37172. {
  37173. format: RGBAFormat,
  37174. type: UnsignedByteType,
  37175. colorSpace: renderer.outputColorSpace,
  37176. stencilBuffer: renderer.stencil,
  37177. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  37178. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  37179. }
  37180. );
  37181. this._xrRenderTarget._isOpaqueFramebuffer = true;
  37182. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  37183. }
  37184. //
  37185. this.setFoveation( this.getFoveation() );
  37186. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  37187. renderer._animation.setContext( session );
  37188. renderer._animation.start();
  37189. this.isPresenting = true;
  37190. this.dispatchEvent( { type: 'sessionstart' } );
  37191. }
  37192. }
  37193. /**
  37194. * This method is called by the renderer per frame and updates the XR camera
  37195. * and it sub cameras based on the given camera. The given camera is the "user"
  37196. * camera created on application level and used for non-XR rendering.
  37197. *
  37198. * @param {PerspectiveCamera} camera - The camera.
  37199. */
  37200. updateCamera( camera ) {
  37201. const session = this._session;
  37202. if ( session === null ) return;
  37203. const depthNear = camera.near;
  37204. const depthFar = camera.far;
  37205. const cameraXR = this._cameraXR;
  37206. const cameraL = this._cameraL;
  37207. const cameraR = this._cameraR;
  37208. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  37209. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  37210. cameraXR.isMultiViewCamera = this._useMultiview;
  37211. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  37212. // Note that the new renderState won't apply until the next frame. See #18320
  37213. session.updateRenderState( {
  37214. depthNear: cameraXR.near,
  37215. depthFar: cameraXR.far
  37216. } );
  37217. this._currentDepthNear = cameraXR.near;
  37218. this._currentDepthFar = cameraXR.far;
  37219. }
  37220. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  37221. cameraXR.layers.mask = camera.layers.mask | 0b110;
  37222. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  37223. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  37224. const parent = camera.parent;
  37225. const cameras = cameraXR.cameras;
  37226. updateCamera( cameraXR, parent );
  37227. for ( let i = 0; i < cameras.length; i ++ ) {
  37228. updateCamera( cameras[ i ], parent );
  37229. }
  37230. // update projection matrix for proper view frustum culling
  37231. if ( cameras.length === 2 ) {
  37232. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  37233. } else {
  37234. // assume single camera setup (AR)
  37235. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  37236. }
  37237. // update user camera and its children
  37238. updateUserCamera( camera, cameraXR, parent );
  37239. }
  37240. /**
  37241. * Returns a WebXR controller for the given controller index.
  37242. *
  37243. * @private
  37244. * @param {number} index - The controller index.
  37245. * @return {WebXRController} The XR controller.
  37246. */
  37247. _getController( index ) {
  37248. let controller = this._controllers[ index ];
  37249. if ( controller === undefined ) {
  37250. controller = new WebXRController();
  37251. this._controllers[ index ] = controller;
  37252. }
  37253. return controller;
  37254. }
  37255. }
  37256. /**
  37257. * Assumes 2 cameras that are parallel and share an X-axis, and that
  37258. * the cameras' projection and world matrices have already been set.
  37259. * And that near and far planes are identical for both cameras.
  37260. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  37261. *
  37262. * @param {ArrayCamera} camera - The camera to update.
  37263. * @param {PerspectiveCamera} cameraL - The left camera.
  37264. * @param {PerspectiveCamera} cameraR - The right camera.
  37265. */
  37266. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  37267. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  37268. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  37269. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  37270. const projL = cameraL.projectionMatrix.elements;
  37271. const projR = cameraR.projectionMatrix.elements;
  37272. // VR systems will have identical far and near planes, and
  37273. // most likely identical top and bottom frustum extents.
  37274. // Use the left camera for these values.
  37275. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  37276. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  37277. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  37278. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  37279. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  37280. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  37281. const left = near * leftFov;
  37282. const right = near * rightFov;
  37283. // Calculate the new camera's position offset from the
  37284. // left camera. xOffset should be roughly half `ipd`.
  37285. const zOffset = ipd / ( - leftFov + rightFov );
  37286. const xOffset = zOffset * - leftFov;
  37287. // TODO: Better way to apply this offset?
  37288. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  37289. camera.translateX( xOffset );
  37290. camera.translateZ( zOffset );
  37291. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  37292. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  37293. // Check if the projection uses an infinite far plane.
  37294. if ( projL[ 10 ] === -1 ) {
  37295. // Use the projection matrix from the left eye.
  37296. // The camera offset is sufficient to include the view volumes
  37297. // of both eyes (assuming symmetric projections).
  37298. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  37299. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  37300. } else {
  37301. // Find the union of the frustum values of the cameras and scale
  37302. // the values so that the near plane's position does not change in world space,
  37303. // although must now be relative to the new union camera.
  37304. const near2 = near + zOffset;
  37305. const far2 = far + zOffset;
  37306. const left2 = left - xOffset;
  37307. const right2 = right + ( ipd - xOffset );
  37308. const top2 = topFov * far / far2 * near2;
  37309. const bottom2 = bottomFov * far / far2 * near2;
  37310. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  37311. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  37312. }
  37313. }
  37314. /**
  37315. * Updates the world matrices for the given camera based on the parent 3D object.
  37316. *
  37317. * @inner
  37318. * @param {Camera} camera - The camera to update.
  37319. * @param {Object3D} parent - The parent 3D object.
  37320. */
  37321. function updateCamera( camera, parent ) {
  37322. if ( parent === null ) {
  37323. camera.matrixWorld.copy( camera.matrix );
  37324. } else {
  37325. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  37326. }
  37327. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  37328. }
  37329. /**
  37330. * Updates the given camera with the transformation of the XR camera and parent object.
  37331. *
  37332. * @inner
  37333. * @param {Camera} camera - The camera to update.
  37334. * @param {ArrayCamera} cameraXR - The XR camera.
  37335. * @param {Object3D} parent - The parent 3D object.
  37336. */
  37337. function updateUserCamera( camera, cameraXR, parent ) {
  37338. if ( parent === null ) {
  37339. camera.matrix.copy( cameraXR.matrixWorld );
  37340. } else {
  37341. camera.matrix.copy( parent.matrixWorld );
  37342. camera.matrix.invert();
  37343. camera.matrix.multiply( cameraXR.matrixWorld );
  37344. }
  37345. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  37346. camera.updateMatrixWorld( true );
  37347. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  37348. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  37349. if ( camera.isPerspectiveCamera ) {
  37350. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  37351. camera.zoom = 1;
  37352. }
  37353. }
  37354. function onSessionEvent( event ) {
  37355. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  37356. if ( controllerIndex === -1 ) {
  37357. return;
  37358. }
  37359. const controller = this._controllers[ controllerIndex ];
  37360. if ( controller !== undefined ) {
  37361. const referenceSpace = this.getReferenceSpace();
  37362. controller.update( event.inputSource, event.frame, referenceSpace );
  37363. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  37364. }
  37365. }
  37366. function onSessionEnd() {
  37367. const session = this._session;
  37368. const renderer = this._renderer;
  37369. session.removeEventListener( 'select', this._onSessionEvent );
  37370. session.removeEventListener( 'selectstart', this._onSessionEvent );
  37371. session.removeEventListener( 'selectend', this._onSessionEvent );
  37372. session.removeEventListener( 'squeeze', this._onSessionEvent );
  37373. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  37374. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  37375. session.removeEventListener( 'end', this._onSessionEnd );
  37376. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  37377. for ( let i = 0; i < this._controllers.length; i ++ ) {
  37378. const inputSource = this._controllerInputSources[ i ];
  37379. if ( inputSource === null ) continue;
  37380. this._controllerInputSources[ i ] = null;
  37381. this._controllers[ i ].disconnect( inputSource );
  37382. }
  37383. this._currentDepthNear = null;
  37384. this._currentDepthFar = null;
  37385. // restore framebuffer/rendering state
  37386. renderer._resetXRState();
  37387. this._session = null;
  37388. this._xrRenderTarget = null;
  37389. // switch layers back to emulated
  37390. if ( this._supportsLayers === true ) {
  37391. for ( const layer of this._layers ) {
  37392. // Recreate layer render target to reset state
  37393. layer.renderTarget = new XRRenderTarget(
  37394. layer.pixelwidth,
  37395. layer.pixelheight,
  37396. {
  37397. format: RGBAFormat,
  37398. type: UnsignedByteType,
  37399. depthTexture: new DepthTexture(
  37400. layer.pixelwidth,
  37401. layer.pixelheight,
  37402. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  37403. undefined,
  37404. undefined,
  37405. undefined,
  37406. undefined,
  37407. undefined,
  37408. undefined,
  37409. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  37410. ),
  37411. stencilBuffer: layer.stencilBuffer,
  37412. resolveDepthBuffer: false,
  37413. resolveStencilBuffer: false
  37414. } );
  37415. layer.renderTarget.isXRRenderTarget = false;
  37416. layer.plane.material = layer.material;
  37417. layer.material.map = layer.renderTarget.texture;
  37418. layer.material.map.offset.y = 1;
  37419. layer.material.map.repeat.y = -1;
  37420. delete layer.xrlayer;
  37421. }
  37422. }
  37423. //
  37424. this.isPresenting = false;
  37425. this._useMultiview = false;
  37426. renderer._animation.stop();
  37427. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  37428. renderer._animation.setContext( this._currentAnimationContext );
  37429. renderer._animation.start();
  37430. renderer.setPixelRatio( this._currentPixelRatio );
  37431. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  37432. this.dispatchEvent( { type: 'sessionend' } );
  37433. }
  37434. function onInputSourcesChange( event ) {
  37435. const controllers = this._controllers;
  37436. const controllerInputSources = this._controllerInputSources;
  37437. // Notify disconnected
  37438. for ( let i = 0; i < event.removed.length; i ++ ) {
  37439. const inputSource = event.removed[ i ];
  37440. const index = controllerInputSources.indexOf( inputSource );
  37441. if ( index >= 0 ) {
  37442. controllerInputSources[ index ] = null;
  37443. controllers[ index ].disconnect( inputSource );
  37444. }
  37445. }
  37446. // Notify connected
  37447. for ( let i = 0; i < event.added.length; i ++ ) {
  37448. const inputSource = event.added[ i ];
  37449. let controllerIndex = controllerInputSources.indexOf( inputSource );
  37450. if ( controllerIndex === -1 ) {
  37451. // Assign input source a controller that currently has no input source
  37452. for ( let i = 0; i < controllers.length; i ++ ) {
  37453. if ( i >= controllerInputSources.length ) {
  37454. controllerInputSources.push( inputSource );
  37455. controllerIndex = i;
  37456. break;
  37457. } else if ( controllerInputSources[ i ] === null ) {
  37458. controllerInputSources[ i ] = inputSource;
  37459. controllerIndex = i;
  37460. break;
  37461. }
  37462. }
  37463. // If all controllers do currently receive input we ignore new ones
  37464. if ( controllerIndex === -1 ) break;
  37465. }
  37466. const controller = controllers[ controllerIndex ];
  37467. if ( controller ) {
  37468. controller.connect( inputSource );
  37469. }
  37470. }
  37471. }
  37472. // Creation method for native WebXR layers
  37473. function createXRLayer( layer ) {
  37474. if ( layer.type === 'quad' ) {
  37475. return this._glBinding.createQuadLayer( {
  37476. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  37477. width: layer.width / 2,
  37478. height: layer.height / 2,
  37479. space: this._referenceSpace,
  37480. viewPixelWidth: layer.pixelwidth,
  37481. viewPixelHeight: layer.pixelheight,
  37482. clearOnAccess: false
  37483. } );
  37484. } else {
  37485. return this._glBinding.createCylinderLayer( {
  37486. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  37487. radius: layer.radius,
  37488. centralAngle: layer.centralAngle,
  37489. aspectRatio: layer.aspectRatio,
  37490. space: this._referenceSpace,
  37491. viewPixelWidth: layer.pixelwidth,
  37492. viewPixelHeight: layer.pixelheight,
  37493. clearOnAccess: false
  37494. } );
  37495. }
  37496. }
  37497. // Animation Loop
  37498. function onAnimationFrame( time, frame ) {
  37499. if ( frame === undefined ) return;
  37500. const cameraXR = this._cameraXR;
  37501. const renderer = this._renderer;
  37502. const backend = renderer.backend;
  37503. const glBaseLayer = this._glBaseLayer;
  37504. const referenceSpace = this.getReferenceSpace();
  37505. const pose = frame.getViewerPose( referenceSpace );
  37506. this._xrFrame = frame;
  37507. if ( pose !== null ) {
  37508. const views = pose.views;
  37509. if ( this._glBaseLayer !== null ) {
  37510. backend.setXRTarget( glBaseLayer.framebuffer );
  37511. }
  37512. let cameraXRNeedsUpdate = false;
  37513. // check if it's necessary to rebuild cameraXR's camera list
  37514. if ( views.length !== cameraXR.cameras.length ) {
  37515. cameraXR.cameras.length = 0;
  37516. cameraXRNeedsUpdate = true;
  37517. }
  37518. for ( let i = 0; i < views.length; i ++ ) {
  37519. const view = views[ i ];
  37520. let viewport;
  37521. if ( this._useLayers === true ) {
  37522. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  37523. viewport = glSubImage.viewport;
  37524. // For side-by-side projection, we only produce a single texture for both eyes.
  37525. if ( i === 0 ) {
  37526. backend.setXRRenderTargetTextures(
  37527. this._xrRenderTarget,
  37528. glSubImage.colorTexture,
  37529. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  37530. );
  37531. }
  37532. } else {
  37533. viewport = glBaseLayer.getViewport( view );
  37534. }
  37535. let camera = this._cameras[ i ];
  37536. if ( camera === undefined ) {
  37537. camera = new PerspectiveCamera();
  37538. camera.layers.enable( i );
  37539. camera.viewport = new Vector4();
  37540. this._cameras[ i ] = camera;
  37541. }
  37542. camera.matrix.fromArray( view.transform.matrix );
  37543. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  37544. camera.projectionMatrix.fromArray( view.projectionMatrix );
  37545. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  37546. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  37547. if ( i === 0 ) {
  37548. cameraXR.matrix.copy( camera.matrix );
  37549. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  37550. }
  37551. if ( cameraXRNeedsUpdate === true ) {
  37552. cameraXR.cameras.push( camera );
  37553. }
  37554. }
  37555. renderer.setOutputRenderTarget( this._xrRenderTarget );
  37556. }
  37557. //
  37558. for ( let i = 0; i < this._controllers.length; i ++ ) {
  37559. const inputSource = this._controllerInputSources[ i ];
  37560. const controller = this._controllers[ i ];
  37561. if ( inputSource !== null && controller !== undefined ) {
  37562. controller.update( inputSource, frame, referenceSpace );
  37563. }
  37564. }
  37565. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  37566. if ( frame.detectedPlanes ) {
  37567. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  37568. }
  37569. this._xrFrame = null;
  37570. }
  37571. const _scene = /*@__PURE__*/ new Scene();
  37572. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  37573. const _screen = /*@__PURE__*/ new Vector4();
  37574. const _frustum = /*@__PURE__*/ new Frustum();
  37575. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  37576. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  37577. const _vector4 = /*@__PURE__*/ new Vector4();
  37578. /**
  37579. * Base class for renderers.
  37580. */
  37581. class Renderer {
  37582. /**
  37583. * Renderer options.
  37584. *
  37585. * @typedef {Object} Renderer~Options
  37586. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  37587. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  37588. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  37589. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  37590. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  37591. * @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
  37592. * to overwrite the default.
  37593. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  37594. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  37595. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  37596. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  37597. */
  37598. /**
  37599. * Constructs a new renderer.
  37600. *
  37601. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  37602. * @param {Renderer~Options} [parameters] - The configuration parameter.
  37603. */
  37604. constructor( backend, parameters = {} ) {
  37605. /**
  37606. * This flag can be used for type testing.
  37607. *
  37608. * @type {boolean}
  37609. * @readonly
  37610. * @default true
  37611. */
  37612. this.isRenderer = true;
  37613. //
  37614. const {
  37615. logarithmicDepthBuffer = false,
  37616. alpha = true,
  37617. depth = true,
  37618. stencil = false,
  37619. antialias = false,
  37620. samples = 0,
  37621. getFallback = null,
  37622. colorBufferType = HalfFloatType,
  37623. multiview = false
  37624. } = parameters;
  37625. /**
  37626. * A reference to the canvas element the renderer is drawing to.
  37627. * This value of this property will automatically be created by
  37628. * the renderer.
  37629. *
  37630. * @type {HTMLCanvasElement|OffscreenCanvas}
  37631. */
  37632. this.domElement = backend.getDomElement();
  37633. /**
  37634. * A reference to the current backend.
  37635. *
  37636. * @type {Backend}
  37637. */
  37638. this.backend = backend;
  37639. /**
  37640. * The number of MSAA samples.
  37641. *
  37642. * @type {number}
  37643. * @default 0
  37644. */
  37645. this.samples = samples || ( antialias === true ) ? 4 : 0;
  37646. /**
  37647. * Whether the renderer should automatically clear the current rendering target
  37648. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  37649. * or the current bound render target (custom framebuffer).
  37650. *
  37651. * @type {boolean}
  37652. * @default true
  37653. */
  37654. this.autoClear = true;
  37655. /**
  37656. * When `autoClear` is set to `true`, this property defines whether the renderer
  37657. * should clear the color buffer.
  37658. *
  37659. * @type {boolean}
  37660. * @default true
  37661. */
  37662. this.autoClearColor = true;
  37663. /**
  37664. * When `autoClear` is set to `true`, this property defines whether the renderer
  37665. * should clear the depth buffer.
  37666. *
  37667. * @type {boolean}
  37668. * @default true
  37669. */
  37670. this.autoClearDepth = true;
  37671. /**
  37672. * When `autoClear` is set to `true`, this property defines whether the renderer
  37673. * should clear the stencil buffer.
  37674. *
  37675. * @type {boolean}
  37676. * @default true
  37677. */
  37678. this.autoClearStencil = true;
  37679. /**
  37680. * Whether the default framebuffer should be transparent or opaque.
  37681. *
  37682. * @type {boolean}
  37683. * @default true
  37684. */
  37685. this.alpha = alpha;
  37686. /**
  37687. * Whether logarithmic depth buffer is enabled or not.
  37688. *
  37689. * @type {boolean}
  37690. * @default false
  37691. */
  37692. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  37693. /**
  37694. * Defines the output color space of the renderer.
  37695. *
  37696. * @type {string}
  37697. * @default SRGBColorSpace
  37698. */
  37699. this.outputColorSpace = SRGBColorSpace;
  37700. /**
  37701. * Defines the tone mapping of the renderer.
  37702. *
  37703. * @type {number}
  37704. * @default NoToneMapping
  37705. */
  37706. this.toneMapping = NoToneMapping;
  37707. /**
  37708. * Defines the tone mapping exposure.
  37709. *
  37710. * @type {number}
  37711. * @default 1
  37712. */
  37713. this.toneMappingExposure = 1.0;
  37714. /**
  37715. * Whether the renderer should sort its render lists or not.
  37716. *
  37717. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  37718. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  37719. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  37720. * e.g. manually determining each object's rendering order.
  37721. *
  37722. * @type {boolean}
  37723. * @default true
  37724. */
  37725. this.sortObjects = true;
  37726. /**
  37727. * Whether the default framebuffer should have a depth buffer or not.
  37728. *
  37729. * @type {boolean}
  37730. * @default true
  37731. */
  37732. this.depth = depth;
  37733. /**
  37734. * Whether the default framebuffer should have a stencil buffer or not.
  37735. *
  37736. * @type {boolean}
  37737. * @default false
  37738. */
  37739. this.stencil = stencil;
  37740. /**
  37741. * Holds a series of statistical information about the GPU memory
  37742. * and the rendering process. Useful for debugging and monitoring.
  37743. *
  37744. * @type {Info}
  37745. */
  37746. this.info = new Info();
  37747. /**
  37748. * Stores override nodes for specific transformations or calculations.
  37749. * These nodes can be used to replace default behavior in the rendering pipeline.
  37750. *
  37751. * @type {Object}
  37752. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  37753. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  37754. */
  37755. this.overrideNodes = {
  37756. modelViewMatrix: null,
  37757. modelNormalViewMatrix: null
  37758. };
  37759. /**
  37760. * The node library defines how certain library objects like materials, lights
  37761. * or tone mapping functions are mapped to node types. This is required since
  37762. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  37763. * be part of the scene graph, they are internally represented as nodes for
  37764. * further processing.
  37765. *
  37766. * @type {NodeLibrary}
  37767. */
  37768. this.library = new NodeLibrary();
  37769. /**
  37770. * A map-like data structure for managing lights.
  37771. *
  37772. * @type {Lighting}
  37773. */
  37774. this.lighting = new Lighting();
  37775. // internals
  37776. /**
  37777. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  37778. *
  37779. * @private
  37780. * @type {?Function}
  37781. */
  37782. this._getFallback = getFallback;
  37783. /**
  37784. * The renderer's pixel ratio.
  37785. *
  37786. * @private
  37787. * @type {number}
  37788. * @default 1
  37789. */
  37790. this._pixelRatio = 1;
  37791. /**
  37792. * The width of the renderer's default framebuffer in logical pixel unit.
  37793. *
  37794. * @private
  37795. * @type {number}
  37796. */
  37797. this._width = this.domElement.width;
  37798. /**
  37799. * The height of the renderer's default framebuffer in logical pixel unit.
  37800. *
  37801. * @private
  37802. * @type {number}
  37803. */
  37804. this._height = this.domElement.height;
  37805. /**
  37806. * The viewport of the renderer in logical pixel unit.
  37807. *
  37808. * @private
  37809. * @type {Vector4}
  37810. */
  37811. this._viewport = new Vector4( 0, 0, this._width, this._height );
  37812. /**
  37813. * The scissor rectangle of the renderer in logical pixel unit.
  37814. *
  37815. * @private
  37816. * @type {Vector4}
  37817. */
  37818. this._scissor = new Vector4( 0, 0, this._width, this._height );
  37819. /**
  37820. * Whether the scissor test should be enabled or not.
  37821. *
  37822. * @private
  37823. * @type {boolean}
  37824. */
  37825. this._scissorTest = false;
  37826. /**
  37827. * A reference to a renderer module for managing shader attributes.
  37828. *
  37829. * @private
  37830. * @type {?Attributes}
  37831. * @default null
  37832. */
  37833. this._attributes = null;
  37834. /**
  37835. * A reference to a renderer module for managing geometries.
  37836. *
  37837. * @private
  37838. * @type {?Geometries}
  37839. * @default null
  37840. */
  37841. this._geometries = null;
  37842. /**
  37843. * A reference to a renderer module for managing node related logic.
  37844. *
  37845. * @private
  37846. * @type {?Nodes}
  37847. * @default null
  37848. */
  37849. this._nodes = null;
  37850. /**
  37851. * A reference to a renderer module for managing the internal animation loop.
  37852. *
  37853. * @private
  37854. * @type {?Animation}
  37855. * @default null
  37856. */
  37857. this._animation = null;
  37858. /**
  37859. * A reference to a renderer module for managing shader program bindings.
  37860. *
  37861. * @private
  37862. * @type {?Bindings}
  37863. * @default null
  37864. */
  37865. this._bindings = null;
  37866. /**
  37867. * A reference to a renderer module for managing render objects.
  37868. *
  37869. * @private
  37870. * @type {?RenderObjects}
  37871. * @default null
  37872. */
  37873. this._objects = null;
  37874. /**
  37875. * A reference to a renderer module for managing render and compute pipelines.
  37876. *
  37877. * @private
  37878. * @type {?Pipelines}
  37879. * @default null
  37880. */
  37881. this._pipelines = null;
  37882. /**
  37883. * A reference to a renderer module for managing render bundles.
  37884. *
  37885. * @private
  37886. * @type {?RenderBundles}
  37887. * @default null
  37888. */
  37889. this._bundles = null;
  37890. /**
  37891. * A reference to a renderer module for managing render lists.
  37892. *
  37893. * @private
  37894. * @type {?RenderLists}
  37895. * @default null
  37896. */
  37897. this._renderLists = null;
  37898. /**
  37899. * A reference to a renderer module for managing render contexts.
  37900. *
  37901. * @private
  37902. * @type {?RenderContexts}
  37903. * @default null
  37904. */
  37905. this._renderContexts = null;
  37906. /**
  37907. * A reference to a renderer module for managing textures.
  37908. *
  37909. * @private
  37910. * @type {?Textures}
  37911. * @default null
  37912. */
  37913. this._textures = null;
  37914. /**
  37915. * A reference to a renderer module for backgrounds.
  37916. *
  37917. * @private
  37918. * @type {?Background}
  37919. * @default null
  37920. */
  37921. this._background = null;
  37922. /**
  37923. * This fullscreen quad is used for internal render passes
  37924. * like the tone mapping and color space output pass.
  37925. *
  37926. * @private
  37927. * @type {QuadMesh}
  37928. */
  37929. this._quad = new QuadMesh( new NodeMaterial() );
  37930. this._quad.material.name = 'Renderer_output';
  37931. /**
  37932. * A reference to the current render context.
  37933. *
  37934. * @private
  37935. * @type {?RenderContext}
  37936. * @default null
  37937. */
  37938. this._currentRenderContext = null;
  37939. /**
  37940. * A custom sort function for the opaque render list.
  37941. *
  37942. * @private
  37943. * @type {?Function}
  37944. * @default null
  37945. */
  37946. this._opaqueSort = null;
  37947. /**
  37948. * A custom sort function for the transparent render list.
  37949. *
  37950. * @private
  37951. * @type {?Function}
  37952. * @default null
  37953. */
  37954. this._transparentSort = null;
  37955. /**
  37956. * The framebuffer target.
  37957. *
  37958. * @private
  37959. * @type {?RenderTarget}
  37960. * @default null
  37961. */
  37962. this._frameBufferTarget = null;
  37963. const alphaClear = this.alpha === true ? 0 : 1;
  37964. /**
  37965. * The clear color value.
  37966. *
  37967. * @private
  37968. * @type {Color4}
  37969. */
  37970. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37971. /**
  37972. * The clear depth value.
  37973. *
  37974. * @private
  37975. * @type {number}
  37976. * @default 1
  37977. */
  37978. this._clearDepth = 1;
  37979. /**
  37980. * The clear stencil value.
  37981. *
  37982. * @private
  37983. * @type {number}
  37984. * @default 0
  37985. */
  37986. this._clearStencil = 0;
  37987. /**
  37988. * The current render target.
  37989. *
  37990. * @private
  37991. * @type {?RenderTarget}
  37992. * @default null
  37993. */
  37994. this._renderTarget = null;
  37995. /**
  37996. * The active cube face.
  37997. *
  37998. * @private
  37999. * @type {number}
  38000. * @default 0
  38001. */
  38002. this._activeCubeFace = 0;
  38003. /**
  38004. * The active mipmap level.
  38005. *
  38006. * @private
  38007. * @type {number}
  38008. * @default 0
  38009. */
  38010. this._activeMipmapLevel = 0;
  38011. /**
  38012. * The current output render target.
  38013. *
  38014. * @private
  38015. * @type {?RenderTarget}
  38016. * @default null
  38017. */
  38018. this._outputRenderTarget = null;
  38019. /**
  38020. * The MRT setting.
  38021. *
  38022. * @private
  38023. * @type {?MRTNode}
  38024. * @default null
  38025. */
  38026. this._mrt = null;
  38027. /**
  38028. * This function defines how a render object is going
  38029. * to be rendered.
  38030. *
  38031. * @private
  38032. * @type {?Function}
  38033. * @default null
  38034. */
  38035. this._renderObjectFunction = null;
  38036. /**
  38037. * Used to keep track of the current render object function.
  38038. *
  38039. * @private
  38040. * @type {?Function}
  38041. * @default null
  38042. */
  38043. this._currentRenderObjectFunction = null;
  38044. /**
  38045. * Used to keep track of the current render bundle.
  38046. *
  38047. * @private
  38048. * @type {?RenderBundle}
  38049. * @default null
  38050. */
  38051. this._currentRenderBundle = null;
  38052. /**
  38053. * Next to `_renderObjectFunction()`, this function provides another hook
  38054. * for influencing the render process of a render object. It is meant for internal
  38055. * use and only relevant for `compileAsync()` right now. Instead of using
  38056. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  38057. * a different function might be used which performs no draw but just the node
  38058. * and pipeline updates.
  38059. *
  38060. * @private
  38061. * @type {?Function}
  38062. * @default null
  38063. */
  38064. this._handleObjectFunction = this._renderObjectDirect;
  38065. /**
  38066. * Indicates whether the device has been lost or not. In WebGL terms, the device
  38067. * lost is considered as a context lost. When this is set to `true`, rendering
  38068. * isn't possible anymore.
  38069. *
  38070. * @private
  38071. * @type {boolean}
  38072. * @default false
  38073. */
  38074. this._isDeviceLost = false;
  38075. /**
  38076. * A callback function that defines what should happen when a device/context lost occurs.
  38077. *
  38078. * @type {Function}
  38079. */
  38080. this.onDeviceLost = this._onDeviceLost;
  38081. /**
  38082. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  38083. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  38084. * This will reduce rendering quality though.
  38085. *
  38086. * @private
  38087. * @type {number}
  38088. * @default HalfFloatType
  38089. */
  38090. this._colorBufferType = colorBufferType;
  38091. /**
  38092. * Whether the renderer has been initialized or not.
  38093. *
  38094. * @private
  38095. * @type {boolean}
  38096. * @default false
  38097. */
  38098. this._initialized = false;
  38099. /**
  38100. * A reference to the promise which initializes the renderer.
  38101. *
  38102. * @private
  38103. * @type {?Promise<this>}
  38104. * @default null
  38105. */
  38106. this._initPromise = null;
  38107. /**
  38108. * An array of compilation promises which are used in `compileAsync()`.
  38109. *
  38110. * @private
  38111. * @type {?Array<Promise>}
  38112. * @default null
  38113. */
  38114. this._compilationPromises = null;
  38115. /**
  38116. * Whether the renderer should render transparent render objects or not.
  38117. *
  38118. * @type {boolean}
  38119. * @default true
  38120. */
  38121. this.transparent = true;
  38122. /**
  38123. * Whether the renderer should render opaque render objects or not.
  38124. *
  38125. * @type {boolean}
  38126. * @default true
  38127. */
  38128. this.opaque = true;
  38129. /**
  38130. * Shadow map configuration
  38131. * @typedef {Object} ShadowMapConfig
  38132. * @property {boolean} enabled - Whether to globally enable shadows or not.
  38133. * @property {number} type - The shadow map type.
  38134. */
  38135. /**
  38136. * The renderer's shadow configuration.
  38137. *
  38138. * @type {ShadowMapConfig}
  38139. */
  38140. this.shadowMap = {
  38141. enabled: false,
  38142. type: PCFShadowMap
  38143. };
  38144. /**
  38145. * XR configuration.
  38146. * @typedef {Object} XRConfig
  38147. * @property {boolean} enabled - Whether to globally enable XR or not.
  38148. */
  38149. /**
  38150. * The renderer's XR manager.
  38151. *
  38152. * @type {XRManager}
  38153. */
  38154. this.xr = new XRManager( this, multiview );
  38155. /**
  38156. * Debug configuration.
  38157. * @typedef {Object} DebugConfig
  38158. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  38159. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  38160. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  38161. */
  38162. /**
  38163. * The renderer's debug configuration.
  38164. *
  38165. * @type {DebugConfig}
  38166. */
  38167. this.debug = {
  38168. checkShaderErrors: true,
  38169. onShaderError: null,
  38170. getShaderAsync: async ( scene, camera, object ) => {
  38171. await this.compileAsync( scene, camera );
  38172. const renderList = this._renderLists.get( scene, camera );
  38173. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  38174. const material = scene.overrideMaterial || object.material;
  38175. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  38176. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  38177. return { fragmentShader, vertexShader };
  38178. }
  38179. };
  38180. }
  38181. /**
  38182. * Initializes the renderer so it is ready for usage.
  38183. *
  38184. * @async
  38185. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  38186. */
  38187. async init() {
  38188. if ( this._initialized ) {
  38189. throw new Error( 'Renderer: Backend has already been initialized.' );
  38190. }
  38191. if ( this._initPromise !== null ) {
  38192. return this._initPromise;
  38193. }
  38194. this._initPromise = new Promise( async ( resolve, reject ) => {
  38195. let backend = this.backend;
  38196. try {
  38197. await backend.init( this );
  38198. } catch ( error ) {
  38199. if ( this._getFallback !== null ) {
  38200. // try the fallback
  38201. try {
  38202. this.backend = backend = this._getFallback( error );
  38203. await backend.init( this );
  38204. } catch ( error ) {
  38205. reject( error );
  38206. return;
  38207. }
  38208. } else {
  38209. reject( error );
  38210. return;
  38211. }
  38212. }
  38213. this._nodes = new Nodes( this, backend );
  38214. this._animation = new Animation( this._nodes, this.info );
  38215. this._attributes = new Attributes( backend );
  38216. this._background = new Background( this, this._nodes );
  38217. this._geometries = new Geometries( this._attributes, this.info );
  38218. this._textures = new Textures( this, backend, this.info );
  38219. this._pipelines = new Pipelines( backend, this._nodes );
  38220. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  38221. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  38222. this._renderLists = new RenderLists( this.lighting );
  38223. this._bundles = new RenderBundles();
  38224. this._renderContexts = new RenderContexts();
  38225. //
  38226. this._animation.start();
  38227. this._initialized = true;
  38228. resolve( this );
  38229. } );
  38230. return this._initPromise;
  38231. }
  38232. /**
  38233. * The coordinate system of the renderer. The value of this property
  38234. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  38235. * `THREE.WebGPUCoordinateSystem`.
  38236. *
  38237. * @readonly
  38238. * @type {number}
  38239. */
  38240. get coordinateSystem() {
  38241. return this.backend.coordinateSystem;
  38242. }
  38243. /**
  38244. * Compiles all materials in the given scene. This can be useful to avoid a
  38245. * phenomenon which is called "shader compilation stutter", which occurs when
  38246. * rendering an object with a new shader for the first time.
  38247. *
  38248. * If you want to add a 3D object to an existing scene, use the third optional
  38249. * parameter for applying the target scene. Note that the (target) scene's lighting
  38250. * and environment must be configured before calling this method.
  38251. *
  38252. * @async
  38253. * @param {Object3D} scene - The scene or 3D object to precompile.
  38254. * @param {Camera} camera - The camera that is used to render the scene.
  38255. * @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.
  38256. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  38257. */
  38258. async compileAsync( scene, camera, targetScene = null ) {
  38259. if ( this._isDeviceLost === true ) return;
  38260. if ( this._initialized === false ) await this.init();
  38261. // preserve render tree
  38262. const nodeFrame = this._nodes.nodeFrame;
  38263. const previousRenderId = nodeFrame.renderId;
  38264. const previousRenderContext = this._currentRenderContext;
  38265. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  38266. const previousCompilationPromises = this._compilationPromises;
  38267. //
  38268. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  38269. if ( targetScene === null ) targetScene = scene;
  38270. const renderTarget = this._renderTarget;
  38271. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  38272. const activeMipmapLevel = this._activeMipmapLevel;
  38273. const compilationPromises = [];
  38274. this._currentRenderContext = renderContext;
  38275. this._currentRenderObjectFunction = this.renderObject;
  38276. this._handleObjectFunction = this._createObjectPipeline;
  38277. this._compilationPromises = compilationPromises;
  38278. nodeFrame.renderId ++;
  38279. //
  38280. nodeFrame.update();
  38281. //
  38282. renderContext.depth = this.depth;
  38283. renderContext.stencil = this.stencil;
  38284. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38285. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  38286. //
  38287. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38288. //
  38289. const renderList = this._renderLists.get( scene, camera );
  38290. renderList.begin();
  38291. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  38292. // include lights from target scene
  38293. if ( targetScene !== scene ) {
  38294. targetScene.traverseVisible( function ( object ) {
  38295. if ( object.isLight && object.layers.test( camera.layers ) ) {
  38296. renderList.pushLight( object );
  38297. }
  38298. } );
  38299. }
  38300. renderList.finish();
  38301. //
  38302. if ( renderTarget !== null ) {
  38303. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  38304. const renderTargetData = this._textures.get( renderTarget );
  38305. renderContext.textures = renderTargetData.textures;
  38306. renderContext.depthTexture = renderTargetData.depthTexture;
  38307. } else {
  38308. renderContext.textures = null;
  38309. renderContext.depthTexture = null;
  38310. }
  38311. //
  38312. this._background.update( sceneRef, renderList, renderContext );
  38313. // process render lists
  38314. const opaqueObjects = renderList.opaque;
  38315. const transparentObjects = renderList.transparent;
  38316. const transparentDoublePassObjects = renderList.transparentDoublePass;
  38317. const lightsNode = renderList.lightsNode;
  38318. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38319. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  38320. // restore render tree
  38321. nodeFrame.renderId = previousRenderId;
  38322. this._currentRenderContext = previousRenderContext;
  38323. this._currentRenderObjectFunction = previousRenderObjectFunction;
  38324. this._compilationPromises = previousCompilationPromises;
  38325. this._handleObjectFunction = this._renderObjectDirect;
  38326. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  38327. await Promise.all( compilationPromises );
  38328. }
  38329. /**
  38330. * Renders the scene in an async fashion.
  38331. *
  38332. * @async
  38333. * @param {Object3D} scene - The scene or 3D object to render.
  38334. * @param {Camera} camera - The camera.
  38335. * @return {Promise} A Promise that resolves when the render has been finished.
  38336. */
  38337. async renderAsync( scene, camera ) {
  38338. if ( this._initialized === false ) await this.init();
  38339. this._renderScene( scene, camera );
  38340. }
  38341. /**
  38342. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  38343. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  38344. *
  38345. * @async
  38346. * @return {Promise} A Promise that resolves when synchronization has been finished.
  38347. */
  38348. async waitForGPU() {
  38349. await this.backend.waitForGPU();
  38350. }
  38351. /**
  38352. * Enables or disables high precision for model-view and normal-view matrices.
  38353. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  38354. *
  38355. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  38356. *
  38357. * @param {boolean} value - Whether to enable or disable high precision.
  38358. * @type {boolean}
  38359. */
  38360. set highPrecision( value ) {
  38361. if ( value === true ) {
  38362. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  38363. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  38364. } else if ( this.highPrecision ) {
  38365. this.overrideNodes.modelViewMatrix = null;
  38366. this.overrideNodes.modelNormalViewMatrix = null;
  38367. }
  38368. }
  38369. /**
  38370. * Returns whether high precision is enabled or not.
  38371. *
  38372. * @return {boolean} Whether high precision is enabled or not.
  38373. * @type {boolean}
  38374. */
  38375. get highPrecision() {
  38376. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  38377. }
  38378. /**
  38379. * Sets the given MRT configuration.
  38380. *
  38381. * @param {MRTNode} mrt - The MRT node to set.
  38382. * @return {Renderer} A reference to this renderer.
  38383. */
  38384. setMRT( mrt ) {
  38385. this._mrt = mrt;
  38386. return this;
  38387. }
  38388. /**
  38389. * Returns the MRT configuration.
  38390. *
  38391. * @return {MRTNode} The MRT configuration.
  38392. */
  38393. getMRT() {
  38394. return this._mrt;
  38395. }
  38396. /**
  38397. * Returns the color buffer type.
  38398. *
  38399. * @return {number} The color buffer type.
  38400. */
  38401. getColorBufferType() {
  38402. return this._colorBufferType;
  38403. }
  38404. /**
  38405. * Default implementation of the device lost callback.
  38406. *
  38407. * @private
  38408. * @param {Object} info - Information about the context lost.
  38409. */
  38410. _onDeviceLost( info ) {
  38411. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  38412. if ( info.reason ) {
  38413. errorMessage += `\nReason: ${info.reason}`;
  38414. }
  38415. console.error( errorMessage );
  38416. this._isDeviceLost = true;
  38417. }
  38418. /**
  38419. * Renders the given render bundle.
  38420. *
  38421. * @private
  38422. * @param {Object} bundle - Render bundle data.
  38423. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  38424. * @param {LightsNode} lightsNode - The lights node.
  38425. */
  38426. _renderBundle( bundle, sceneRef, lightsNode ) {
  38427. const { bundleGroup, camera, renderList } = bundle;
  38428. const renderContext = this._currentRenderContext;
  38429. //
  38430. const renderBundle = this._bundles.get( bundleGroup, camera );
  38431. const renderBundleData = this.backend.get( renderBundle );
  38432. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  38433. //
  38434. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  38435. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  38436. renderBundleData.renderContexts.add( renderContext );
  38437. if ( renderBundleNeedsUpdate ) {
  38438. this.backend.beginBundle( renderContext );
  38439. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  38440. renderBundleData.renderObjects = [];
  38441. }
  38442. this._currentRenderBundle = renderBundle;
  38443. const {
  38444. transparentDoublePass: transparentDoublePassObjects,
  38445. transparent: transparentObjects,
  38446. opaque: opaqueObjects
  38447. } = renderList;
  38448. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38449. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  38450. this._currentRenderBundle = null;
  38451. //
  38452. this.backend.finishBundle( renderContext, renderBundle );
  38453. renderBundleData.version = bundleGroup.version;
  38454. } else {
  38455. const { renderObjects } = renderBundleData;
  38456. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  38457. const renderObject = renderObjects[ i ];
  38458. if ( this._nodes.needsRefresh( renderObject ) ) {
  38459. this._nodes.updateBefore( renderObject );
  38460. this._nodes.updateForRender( renderObject );
  38461. this._bindings.updateForRender( renderObject );
  38462. this._nodes.updateAfter( renderObject );
  38463. }
  38464. }
  38465. }
  38466. this.backend.addBundle( renderContext, renderBundle );
  38467. }
  38468. /**
  38469. * Renders the scene or 3D object with the given camera. This method can only be called
  38470. * if the renderer has been initialized.
  38471. *
  38472. * The target of the method is the default framebuffer (meaning the canvas)
  38473. * or alternatively a render target when specified via `setRenderTarget()`.
  38474. *
  38475. * @param {Object3D} scene - The scene or 3D object to render.
  38476. * @param {Camera} camera - The camera to render the scene with.
  38477. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  38478. * Only returned when the renderer has not been initialized.
  38479. */
  38480. render( scene, camera ) {
  38481. if ( this._initialized === false ) {
  38482. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  38483. return this.renderAsync( scene, camera );
  38484. }
  38485. this._renderScene( scene, camera );
  38486. }
  38487. /**
  38488. * Returns an internal render target which is used when computing the output tone mapping
  38489. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  38490. * pass and not inline to achieve more correct results.
  38491. *
  38492. * @private
  38493. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  38494. */
  38495. _getFrameBufferTarget() {
  38496. const { currentToneMapping, currentColorSpace } = this;
  38497. const useToneMapping = currentToneMapping !== NoToneMapping;
  38498. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  38499. if ( useToneMapping === false && useColorSpace === false ) return null;
  38500. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  38501. const { depth, stencil } = this;
  38502. let frameBufferTarget = this._frameBufferTarget;
  38503. if ( frameBufferTarget === null ) {
  38504. frameBufferTarget = new RenderTarget( width, height, {
  38505. depthBuffer: depth,
  38506. stencilBuffer: stencil,
  38507. type: this._colorBufferType,
  38508. format: RGBAFormat,
  38509. colorSpace: ColorManagement.workingColorSpace,
  38510. generateMipmaps: false,
  38511. minFilter: LinearFilter,
  38512. magFilter: LinearFilter,
  38513. samples: this.samples
  38514. } );
  38515. frameBufferTarget.isPostProcessingRenderTarget = true;
  38516. this._frameBufferTarget = frameBufferTarget;
  38517. }
  38518. const outputRenderTarget = this.getOutputRenderTarget();
  38519. frameBufferTarget.depthBuffer = depth;
  38520. frameBufferTarget.stencilBuffer = stencil;
  38521. if ( outputRenderTarget !== null ) {
  38522. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  38523. } else {
  38524. frameBufferTarget.setSize( width, height, 1 );
  38525. }
  38526. frameBufferTarget.viewport.copy( this._viewport );
  38527. frameBufferTarget.scissor.copy( this._scissor );
  38528. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  38529. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  38530. frameBufferTarget.scissorTest = this._scissorTest;
  38531. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  38532. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  38533. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  38534. return frameBufferTarget;
  38535. }
  38536. /**
  38537. * Renders the scene or 3D object with the given camera.
  38538. *
  38539. * @private
  38540. * @param {Object3D} scene - The scene or 3D object to render.
  38541. * @param {Camera} camera - The camera to render the scene with.
  38542. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  38543. * @return {RenderContext} The current render context.
  38544. */
  38545. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  38546. if ( this._isDeviceLost === true ) return;
  38547. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  38548. // preserve render tree
  38549. const nodeFrame = this._nodes.nodeFrame;
  38550. const previousRenderId = nodeFrame.renderId;
  38551. const previousRenderContext = this._currentRenderContext;
  38552. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  38553. //
  38554. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  38555. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  38556. const activeCubeFace = this._activeCubeFace;
  38557. const activeMipmapLevel = this._activeMipmapLevel;
  38558. //
  38559. let renderTarget;
  38560. if ( frameBufferTarget !== null ) {
  38561. renderTarget = frameBufferTarget;
  38562. this.setRenderTarget( renderTarget );
  38563. } else {
  38564. renderTarget = outputRenderTarget;
  38565. }
  38566. //
  38567. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  38568. this._currentRenderContext = renderContext;
  38569. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  38570. //
  38571. this.info.calls ++;
  38572. this.info.render.calls ++;
  38573. this.info.render.frameCalls ++;
  38574. nodeFrame.renderId = this.info.calls;
  38575. //
  38576. const coordinateSystem = this.coordinateSystem;
  38577. const xr = this.xr;
  38578. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  38579. camera.coordinateSystem = coordinateSystem;
  38580. camera.updateProjectionMatrix();
  38581. if ( camera.isArrayCamera ) {
  38582. for ( const subCamera of camera.cameras ) {
  38583. subCamera.coordinateSystem = coordinateSystem;
  38584. subCamera.updateProjectionMatrix();
  38585. }
  38586. }
  38587. }
  38588. //
  38589. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  38590. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  38591. if ( xr.enabled === true && xr.isPresenting === true ) {
  38592. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  38593. camera = xr.getCamera(); // use XR camera for rendering
  38594. }
  38595. //
  38596. let viewport = this._viewport;
  38597. let scissor = this._scissor;
  38598. let pixelRatio = this._pixelRatio;
  38599. if ( renderTarget !== null ) {
  38600. viewport = renderTarget.viewport;
  38601. scissor = renderTarget.scissor;
  38602. pixelRatio = 1;
  38603. }
  38604. this.getDrawingBufferSize( _drawingBufferSize );
  38605. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  38606. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  38607. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  38608. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  38609. renderContext.viewportValue.width >>= activeMipmapLevel;
  38610. renderContext.viewportValue.height >>= activeMipmapLevel;
  38611. renderContext.viewportValue.minDepth = minDepth;
  38612. renderContext.viewportValue.maxDepth = maxDepth;
  38613. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  38614. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  38615. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  38616. renderContext.scissorValue.width >>= activeMipmapLevel;
  38617. renderContext.scissorValue.height >>= activeMipmapLevel;
  38618. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38619. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  38620. //
  38621. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38622. //
  38623. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38624. if ( ! camera.isArrayCamera ) {
  38625. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  38626. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  38627. }
  38628. const renderList = this._renderLists.get( scene, camera );
  38629. renderList.begin();
  38630. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  38631. renderList.finish();
  38632. if ( this.sortObjects === true ) {
  38633. renderList.sort( this._opaqueSort, this._transparentSort );
  38634. }
  38635. //
  38636. if ( renderTarget !== null ) {
  38637. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  38638. const renderTargetData = this._textures.get( renderTarget );
  38639. renderContext.textures = renderTargetData.textures;
  38640. renderContext.depthTexture = renderTargetData.depthTexture;
  38641. renderContext.width = renderTargetData.width;
  38642. renderContext.height = renderTargetData.height;
  38643. renderContext.renderTarget = renderTarget;
  38644. renderContext.depth = renderTarget.depthBuffer;
  38645. renderContext.stencil = renderTarget.stencilBuffer;
  38646. } else {
  38647. renderContext.textures = null;
  38648. renderContext.depthTexture = null;
  38649. renderContext.width = this.domElement.width;
  38650. renderContext.height = this.domElement.height;
  38651. renderContext.depth = this.depth;
  38652. renderContext.stencil = this.stencil;
  38653. }
  38654. renderContext.width >>= activeMipmapLevel;
  38655. renderContext.height >>= activeMipmapLevel;
  38656. renderContext.activeCubeFace = activeCubeFace;
  38657. renderContext.activeMipmapLevel = activeMipmapLevel;
  38658. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  38659. //
  38660. this._background.update( sceneRef, renderList, renderContext );
  38661. //
  38662. renderContext.camera = camera;
  38663. this.backend.beginRender( renderContext );
  38664. // process render lists
  38665. const {
  38666. bundles,
  38667. lightsNode,
  38668. transparentDoublePass: transparentDoublePassObjects,
  38669. transparent: transparentObjects,
  38670. opaque: opaqueObjects
  38671. } = renderList;
  38672. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  38673. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38674. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  38675. // finish render pass
  38676. this.backend.finishRender( renderContext );
  38677. // restore render tree
  38678. nodeFrame.renderId = previousRenderId;
  38679. this._currentRenderContext = previousRenderContext;
  38680. this._currentRenderObjectFunction = previousRenderObjectFunction;
  38681. //
  38682. if ( frameBufferTarget !== null ) {
  38683. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  38684. this._renderOutput( renderTarget );
  38685. }
  38686. //
  38687. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  38688. //
  38689. return renderContext;
  38690. }
  38691. _setXRLayerSize( width, height ) {
  38692. this._width = width;
  38693. this._height = height;
  38694. this.setViewport( 0, 0, width, height );
  38695. }
  38696. /**
  38697. * The output pass performs tone mapping and color space conversion.
  38698. *
  38699. * @private
  38700. * @param {RenderTarget} renderTarget - The current render target.
  38701. */
  38702. _renderOutput( renderTarget ) {
  38703. const quad = this._quad;
  38704. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  38705. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  38706. quad.material.needsUpdate = true;
  38707. }
  38708. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  38709. const currentAutoClear = this.autoClear;
  38710. const currentXR = this.xr.enabled;
  38711. this.autoClear = false;
  38712. this.xr.enabled = false;
  38713. this._renderScene( quad, quad.camera, false );
  38714. this.autoClear = currentAutoClear;
  38715. this.xr.enabled = currentXR;
  38716. }
  38717. /**
  38718. * Returns the maximum available anisotropy for texture filtering.
  38719. *
  38720. * @return {number} The maximum available anisotropy.
  38721. */
  38722. getMaxAnisotropy() {
  38723. return this.backend.getMaxAnisotropy();
  38724. }
  38725. /**
  38726. * Returns the active cube face.
  38727. *
  38728. * @return {number} The active cube face.
  38729. */
  38730. getActiveCubeFace() {
  38731. return this._activeCubeFace;
  38732. }
  38733. /**
  38734. * Returns the active mipmap level.
  38735. *
  38736. * @return {number} The active mipmap level.
  38737. */
  38738. getActiveMipmapLevel() {
  38739. return this._activeMipmapLevel;
  38740. }
  38741. /**
  38742. * Applications are advised to always define the animation loop
  38743. * with this method and not manually with `requestAnimationFrame()`
  38744. * for best compatibility.
  38745. *
  38746. * @async
  38747. * @param {?Function} callback - The application's animation loop.
  38748. * @return {Promise} A Promise that resolves when the set has been executed.
  38749. */
  38750. async setAnimationLoop( callback ) {
  38751. if ( this._initialized === false ) await this.init();
  38752. this._animation.setAnimationLoop( callback );
  38753. }
  38754. /**
  38755. * Can be used to transfer buffer data from a storage buffer attribute
  38756. * from the GPU to the CPU in context of compute shaders.
  38757. *
  38758. * @async
  38759. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38760. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38761. */
  38762. async getArrayBufferAsync( attribute ) {
  38763. return await this.backend.getArrayBufferAsync( attribute );
  38764. }
  38765. /**
  38766. * Returns the rendering context.
  38767. *
  38768. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  38769. */
  38770. getContext() {
  38771. return this.backend.getContext();
  38772. }
  38773. /**
  38774. * Returns the pixel ratio.
  38775. *
  38776. * @return {number} The pixel ratio.
  38777. */
  38778. getPixelRatio() {
  38779. return this._pixelRatio;
  38780. }
  38781. /**
  38782. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  38783. *
  38784. * @param {Vector2} target - The method writes the result in this target object.
  38785. * @return {Vector2} The drawing buffer size.
  38786. */
  38787. getDrawingBufferSize( target ) {
  38788. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  38789. }
  38790. /**
  38791. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  38792. *
  38793. * @param {Vector2} target - The method writes the result in this target object.
  38794. * @return {Vector2} The renderer's size in logical pixels.
  38795. */
  38796. getSize( target ) {
  38797. return target.set( this._width, this._height );
  38798. }
  38799. /**
  38800. * Sets the given pixel ratio and resizes the canvas if necessary.
  38801. *
  38802. * @param {number} [value=1] - The pixel ratio.
  38803. */
  38804. setPixelRatio( value = 1 ) {
  38805. if ( this._pixelRatio === value ) return;
  38806. this._pixelRatio = value;
  38807. this.setSize( this._width, this._height, false );
  38808. }
  38809. /**
  38810. * This method allows to define the drawing buffer size by specifying
  38811. * width, height and pixel ratio all at once. The size of the drawing
  38812. * buffer is computed with this formula:
  38813. * ```js
  38814. * size.x = width * pixelRatio;
  38815. * size.y = height * pixelRatio;
  38816. * ```
  38817. *
  38818. * @param {number} width - The width in logical pixels.
  38819. * @param {number} height - The height in logical pixels.
  38820. * @param {number} pixelRatio - The pixel ratio.
  38821. */
  38822. setDrawingBufferSize( width, height, pixelRatio ) {
  38823. // Renderer can't be resized while presenting in XR.
  38824. if ( this.xr && this.xr.isPresenting ) return;
  38825. this._width = width;
  38826. this._height = height;
  38827. this._pixelRatio = pixelRatio;
  38828. this.domElement.width = Math.floor( width * pixelRatio );
  38829. this.domElement.height = Math.floor( height * pixelRatio );
  38830. this.setViewport( 0, 0, width, height );
  38831. if ( this._initialized ) this.backend.updateSize();
  38832. }
  38833. /**
  38834. * Sets the size of the renderer.
  38835. *
  38836. * @param {number} width - The width in logical pixels.
  38837. * @param {number} height - The height in logical pixels.
  38838. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  38839. */
  38840. setSize( width, height, updateStyle = true ) {
  38841. // Renderer can't be resized while presenting in XR.
  38842. if ( this.xr && this.xr.isPresenting ) return;
  38843. this._width = width;
  38844. this._height = height;
  38845. this.domElement.width = Math.floor( width * this._pixelRatio );
  38846. this.domElement.height = Math.floor( height * this._pixelRatio );
  38847. if ( updateStyle === true ) {
  38848. this.domElement.style.width = width + 'px';
  38849. this.domElement.style.height = height + 'px';
  38850. }
  38851. this.setViewport( 0, 0, width, height );
  38852. if ( this._initialized ) this.backend.updateSize();
  38853. }
  38854. /**
  38855. * Defines a manual sort function for the opaque render list.
  38856. * Pass `null` to use the default sort.
  38857. *
  38858. * @param {Function} method - The sort function.
  38859. */
  38860. setOpaqueSort( method ) {
  38861. this._opaqueSort = method;
  38862. }
  38863. /**
  38864. * Defines a manual sort function for the transparent render list.
  38865. * Pass `null` to use the default sort.
  38866. *
  38867. * @param {Function} method - The sort function.
  38868. */
  38869. setTransparentSort( method ) {
  38870. this._transparentSort = method;
  38871. }
  38872. /**
  38873. * Returns the scissor rectangle.
  38874. *
  38875. * @param {Vector4} target - The method writes the result in this target object.
  38876. * @return {Vector4} The scissor rectangle.
  38877. */
  38878. getScissor( target ) {
  38879. const scissor = this._scissor;
  38880. target.x = scissor.x;
  38881. target.y = scissor.y;
  38882. target.width = scissor.width;
  38883. target.height = scissor.height;
  38884. return target;
  38885. }
  38886. /**
  38887. * Defines the scissor rectangle.
  38888. *
  38889. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  38890. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  38891. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  38892. * @param {number} width - The width of the scissor box in logical pixel unit.
  38893. * @param {number} height - The height of the scissor box in logical pixel unit.
  38894. */
  38895. setScissor( x, y, width, height ) {
  38896. const scissor = this._scissor;
  38897. if ( x.isVector4 ) {
  38898. scissor.copy( x );
  38899. } else {
  38900. scissor.set( x, y, width, height );
  38901. }
  38902. }
  38903. /**
  38904. * Returns the scissor test value.
  38905. *
  38906. * @return {boolean} Whether the scissor test should be enabled or not.
  38907. */
  38908. getScissorTest() {
  38909. return this._scissorTest;
  38910. }
  38911. /**
  38912. * Defines the scissor test.
  38913. *
  38914. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  38915. */
  38916. setScissorTest( boolean ) {
  38917. this._scissorTest = boolean;
  38918. this.backend.setScissorTest( boolean );
  38919. }
  38920. /**
  38921. * Returns the viewport definition.
  38922. *
  38923. * @param {Vector4} target - The method writes the result in this target object.
  38924. * @return {Vector4} The viewport definition.
  38925. */
  38926. getViewport( target ) {
  38927. return target.copy( this._viewport );
  38928. }
  38929. /**
  38930. * Defines the viewport.
  38931. *
  38932. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  38933. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  38934. * @param {number} width - The width of the viewport in logical pixel unit.
  38935. * @param {number} height - The height of the viewport in logical pixel unit.
  38936. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  38937. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  38938. */
  38939. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  38940. const viewport = this._viewport;
  38941. if ( x.isVector4 ) {
  38942. viewport.copy( x );
  38943. } else {
  38944. viewport.set( x, y, width, height );
  38945. }
  38946. viewport.minDepth = minDepth;
  38947. viewport.maxDepth = maxDepth;
  38948. }
  38949. /**
  38950. * Returns the clear color.
  38951. *
  38952. * @param {Color} target - The method writes the result in this target object.
  38953. * @return {Color} The clear color.
  38954. */
  38955. getClearColor( target ) {
  38956. return target.copy( this._clearColor );
  38957. }
  38958. /**
  38959. * Defines the clear color and optionally the clear alpha.
  38960. *
  38961. * @param {Color} color - The clear color.
  38962. * @param {number} [alpha=1] - The clear alpha.
  38963. */
  38964. setClearColor( color, alpha = 1 ) {
  38965. this._clearColor.set( color );
  38966. this._clearColor.a = alpha;
  38967. }
  38968. /**
  38969. * Returns the clear alpha.
  38970. *
  38971. * @return {number} The clear alpha.
  38972. */
  38973. getClearAlpha() {
  38974. return this._clearColor.a;
  38975. }
  38976. /**
  38977. * Defines the clear alpha.
  38978. *
  38979. * @param {number} alpha - The clear alpha.
  38980. */
  38981. setClearAlpha( alpha ) {
  38982. this._clearColor.a = alpha;
  38983. }
  38984. /**
  38985. * Returns the clear depth.
  38986. *
  38987. * @return {number} The clear depth.
  38988. */
  38989. getClearDepth() {
  38990. return this._clearDepth;
  38991. }
  38992. /**
  38993. * Defines the clear depth.
  38994. *
  38995. * @param {number} depth - The clear depth.
  38996. */
  38997. setClearDepth( depth ) {
  38998. this._clearDepth = depth;
  38999. }
  39000. /**
  39001. * Returns the clear stencil.
  39002. *
  39003. * @return {number} The clear stencil.
  39004. */
  39005. getClearStencil() {
  39006. return this._clearStencil;
  39007. }
  39008. /**
  39009. * Defines the clear stencil.
  39010. *
  39011. * @param {number} stencil - The clear stencil.
  39012. */
  39013. setClearStencil( stencil ) {
  39014. this._clearStencil = stencil;
  39015. }
  39016. /**
  39017. * This method performs an occlusion query for the given 3D object.
  39018. * It returns `true` if the given 3D object is fully occluded by other
  39019. * 3D objects in the scene.
  39020. *
  39021. * @param {Object3D} object - The 3D object to test.
  39022. * @return {boolean} Whether the 3D object is fully occluded or not.
  39023. */
  39024. isOccluded( object ) {
  39025. const renderContext = this._currentRenderContext;
  39026. return renderContext && this.backend.isOccluded( renderContext, object );
  39027. }
  39028. /**
  39029. * Performs a manual clear operation. This method ignores `autoClear` properties.
  39030. *
  39031. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  39032. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  39033. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  39034. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39035. * Only returned when the renderer has not been initialized.
  39036. */
  39037. clear( color = true, depth = true, stencil = true ) {
  39038. if ( this._initialized === false ) {
  39039. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  39040. return this.clearAsync( color, depth, stencil );
  39041. }
  39042. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  39043. let renderContext = null;
  39044. if ( renderTarget !== null ) {
  39045. this._textures.updateRenderTarget( renderTarget );
  39046. const renderTargetData = this._textures.get( renderTarget );
  39047. renderContext = this._renderContexts.getForClear( renderTarget );
  39048. renderContext.textures = renderTargetData.textures;
  39049. renderContext.depthTexture = renderTargetData.depthTexture;
  39050. renderContext.width = renderTargetData.width;
  39051. renderContext.height = renderTargetData.height;
  39052. renderContext.renderTarget = renderTarget;
  39053. renderContext.depth = renderTarget.depthBuffer;
  39054. renderContext.stencil = renderTarget.stencilBuffer;
  39055. // #30329
  39056. renderContext.clearColorValue = this.backend.getClearColor();
  39057. renderContext.activeCubeFace = this.getActiveCubeFace();
  39058. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  39059. }
  39060. this.backend.clear( color, depth, stencil, renderContext );
  39061. if ( renderTarget !== null && this._renderTarget === null ) {
  39062. this._renderOutput( renderTarget );
  39063. }
  39064. }
  39065. /**
  39066. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  39067. *
  39068. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39069. * Only returned when the renderer has not been initialized.
  39070. */
  39071. clearColor() {
  39072. return this.clear( true, false, false );
  39073. }
  39074. /**
  39075. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  39076. *
  39077. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39078. * Only returned when the renderer has not been initialized.
  39079. */
  39080. clearDepth() {
  39081. return this.clear( false, true, false );
  39082. }
  39083. /**
  39084. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  39085. *
  39086. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39087. * Only returned when the renderer has not been initialized.
  39088. */
  39089. clearStencil() {
  39090. return this.clear( false, false, true );
  39091. }
  39092. /**
  39093. * Async version of {@link Renderer#clear}.
  39094. *
  39095. * @async
  39096. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  39097. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  39098. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  39099. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39100. */
  39101. async clearAsync( color = true, depth = true, stencil = true ) {
  39102. if ( this._initialized === false ) await this.init();
  39103. this.clear( color, depth, stencil );
  39104. }
  39105. /**
  39106. * Async version of {@link Renderer#clearColor}.
  39107. *
  39108. * @async
  39109. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39110. */
  39111. async clearColorAsync() {
  39112. this.clearAsync( true, false, false );
  39113. }
  39114. /**
  39115. * Async version of {@link Renderer#clearDepth}.
  39116. *
  39117. * @async
  39118. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39119. */
  39120. async clearDepthAsync() {
  39121. this.clearAsync( false, true, false );
  39122. }
  39123. /**
  39124. * Async version of {@link Renderer#clearStencil}.
  39125. *
  39126. * @async
  39127. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39128. */
  39129. async clearStencilAsync() {
  39130. this.clearAsync( false, false, true );
  39131. }
  39132. /**
  39133. * The current tone mapping of the renderer. When not producing screen output,
  39134. * the tone mapping is always `NoToneMapping`.
  39135. *
  39136. * @type {number}
  39137. */
  39138. get currentToneMapping() {
  39139. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  39140. }
  39141. /**
  39142. * The current color space of the renderer. When not producing screen output,
  39143. * the color space is always the working color space.
  39144. *
  39145. * @type {string}
  39146. */
  39147. get currentColorSpace() {
  39148. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  39149. }
  39150. /**
  39151. * Returns `true` if the rendering settings are set to screen output.
  39152. *
  39153. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  39154. */
  39155. get isOutputTarget() {
  39156. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  39157. }
  39158. /**
  39159. * Frees all internal resources of the renderer. Call this method if the renderer
  39160. * is no longer in use by your app.
  39161. */
  39162. dispose() {
  39163. this.info.dispose();
  39164. this.backend.dispose();
  39165. this._animation.dispose();
  39166. this._objects.dispose();
  39167. this._pipelines.dispose();
  39168. this._nodes.dispose();
  39169. this._bindings.dispose();
  39170. this._renderLists.dispose();
  39171. this._renderContexts.dispose();
  39172. this._textures.dispose();
  39173. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  39174. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  39175. if ( queryPool !== null ) queryPool.dispose();
  39176. } );
  39177. this.setRenderTarget( null );
  39178. this.setAnimationLoop( null );
  39179. }
  39180. /**
  39181. * Sets the given render target. Calling this method means the renderer does not
  39182. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  39183. * Use `null` as the first argument to reset the state.
  39184. *
  39185. * @param {?RenderTarget} renderTarget - The render target to set.
  39186. * @param {number} [activeCubeFace=0] - The active cube face.
  39187. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  39188. */
  39189. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  39190. this._renderTarget = renderTarget;
  39191. this._activeCubeFace = activeCubeFace;
  39192. this._activeMipmapLevel = activeMipmapLevel;
  39193. }
  39194. /**
  39195. * Returns the current render target.
  39196. *
  39197. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  39198. */
  39199. getRenderTarget() {
  39200. return this._renderTarget;
  39201. }
  39202. /**
  39203. * Sets the output render target for the renderer.
  39204. *
  39205. * @param {Object} renderTarget - The render target to set as the output target.
  39206. */
  39207. setOutputRenderTarget( renderTarget ) {
  39208. this._outputRenderTarget = renderTarget;
  39209. }
  39210. /**
  39211. * Returns the current output target.
  39212. *
  39213. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  39214. */
  39215. getOutputRenderTarget() {
  39216. return this._outputRenderTarget;
  39217. }
  39218. /**
  39219. * Resets the renderer to the initial state before WebXR started.
  39220. *
  39221. */
  39222. _resetXRState() {
  39223. this.backend.setXRTarget( null );
  39224. this.setOutputRenderTarget( null );
  39225. this.setRenderTarget( null );
  39226. this._frameBufferTarget.dispose();
  39227. this._frameBufferTarget = null;
  39228. }
  39229. /**
  39230. * Callback for {@link Renderer#setRenderObjectFunction}.
  39231. *
  39232. * @callback renderObjectFunction
  39233. * @param {Object3D} object - The 3D object.
  39234. * @param {Scene} scene - The scene the 3D object belongs to.
  39235. * @param {Camera} camera - The camera the object should be rendered with.
  39236. * @param {BufferGeometry} geometry - The object's geometry.
  39237. * @param {Material} material - The object's material.
  39238. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39239. * @param {LightsNode} lightsNode - The current lights node.
  39240. * @param {ClippingContext} clippingContext - The clipping context.
  39241. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  39242. */
  39243. /**
  39244. * Sets the given render object function. Calling this method overwrites the default implementation
  39245. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  39246. * if you want to modify the way objects are rendered. For example you can define things like "every
  39247. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  39248. * The custom function must always call `renderObject()` in its implementation.
  39249. *
  39250. * Use `null` as the first argument to reset the state.
  39251. *
  39252. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  39253. */
  39254. setRenderObjectFunction( renderObjectFunction ) {
  39255. this._renderObjectFunction = renderObjectFunction;
  39256. }
  39257. /**
  39258. * Returns the current render object function.
  39259. *
  39260. * @return {?Function} The current render object function. Returns `null` if no function is set.
  39261. */
  39262. getRenderObjectFunction() {
  39263. return this._renderObjectFunction;
  39264. }
  39265. /**
  39266. * Execute a single or an array of compute nodes. This method can only be called
  39267. * if the renderer has been initialized.
  39268. *
  39269. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  39270. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  39271. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  39272. */
  39273. compute( computeNodes, dispatchSizeOrCount = null ) {
  39274. if ( this._isDeviceLost === true ) return;
  39275. if ( this._initialized === false ) {
  39276. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  39277. return this.computeAsync( computeNodes );
  39278. }
  39279. //
  39280. const nodeFrame = this._nodes.nodeFrame;
  39281. const previousRenderId = nodeFrame.renderId;
  39282. //
  39283. this.info.calls ++;
  39284. this.info.compute.calls ++;
  39285. this.info.compute.frameCalls ++;
  39286. nodeFrame.renderId = this.info.calls;
  39287. //
  39288. const backend = this.backend;
  39289. const pipelines = this._pipelines;
  39290. const bindings = this._bindings;
  39291. const nodes = this._nodes;
  39292. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  39293. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  39294. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  39295. }
  39296. backend.beginCompute( computeNodes );
  39297. for ( const computeNode of computeList ) {
  39298. // onInit
  39299. if ( pipelines.has( computeNode ) === false ) {
  39300. const dispose = () => {
  39301. computeNode.removeEventListener( 'dispose', dispose );
  39302. pipelines.delete( computeNode );
  39303. bindings.delete( computeNode );
  39304. nodes.delete( computeNode );
  39305. };
  39306. computeNode.addEventListener( 'dispose', dispose );
  39307. //
  39308. const onInitFn = computeNode.onInitFunction;
  39309. if ( onInitFn !== null ) {
  39310. onInitFn.call( computeNode, { renderer: this } );
  39311. }
  39312. }
  39313. nodes.updateForCompute( computeNode );
  39314. bindings.updateForCompute( computeNode );
  39315. const computeBindings = bindings.getForCompute( computeNode );
  39316. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  39317. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSizeOrCount );
  39318. }
  39319. backend.finishCompute( computeNodes );
  39320. //
  39321. nodeFrame.renderId = previousRenderId;
  39322. }
  39323. /**
  39324. * Execute a single or an array of compute nodes.
  39325. *
  39326. * @async
  39327. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  39328. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  39329. * @return {Promise} A Promise that resolve when the compute has finished.
  39330. */
  39331. async computeAsync( computeNodes, dispatchSizeOrCount = null ) {
  39332. if ( this._initialized === false ) await this.init();
  39333. this.compute( computeNodes, dispatchSizeOrCount );
  39334. }
  39335. /**
  39336. * Checks if the given feature is supported by the selected backend.
  39337. *
  39338. * @async
  39339. * @param {string} name - The feature's name.
  39340. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  39341. */
  39342. async hasFeatureAsync( name ) {
  39343. if ( this._initialized === false ) await this.init();
  39344. return this.backend.hasFeature( name );
  39345. }
  39346. async resolveTimestampsAsync( type = 'render' ) {
  39347. if ( this._initialized === false ) await this.init();
  39348. return this.backend.resolveTimestampsAsync( type );
  39349. }
  39350. /**
  39351. * Checks if the given feature is supported by the selected backend. If the
  39352. * renderer has not been initialized, this method always returns `false`.
  39353. *
  39354. * @param {string} name - The feature's name.
  39355. * @return {boolean} Whether the feature is supported or not.
  39356. */
  39357. hasFeature( name ) {
  39358. if ( this._initialized === false ) {
  39359. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  39360. return false;
  39361. }
  39362. return this.backend.hasFeature( name );
  39363. }
  39364. /**
  39365. * Returns `true` when the renderer has been initialized.
  39366. *
  39367. * @return {boolean} Whether the renderer has been initialized or not.
  39368. */
  39369. hasInitialized() {
  39370. return this._initialized;
  39371. }
  39372. /**
  39373. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  39374. * (which can cause noticeable lags due to decode and GPU upload overhead).
  39375. *
  39376. * @async
  39377. * @param {Texture} texture - The texture.
  39378. * @return {Promise} A Promise that resolves when the texture has been initialized.
  39379. */
  39380. async initTextureAsync( texture ) {
  39381. if ( this._initialized === false ) await this.init();
  39382. this._textures.updateTexture( texture );
  39383. }
  39384. /**
  39385. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  39386. * (which can cause noticeable lags due to decode and GPU upload overhead).
  39387. *
  39388. * This method can only be used if the renderer has been initialized.
  39389. *
  39390. * @param {Texture} texture - The texture.
  39391. */
  39392. initTexture( texture ) {
  39393. if ( this._initialized === false ) {
  39394. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  39395. }
  39396. this._textures.updateTexture( texture );
  39397. }
  39398. /**
  39399. * Copies the current bound framebuffer into the given texture.
  39400. *
  39401. * @param {FramebufferTexture} framebufferTexture - The texture.
  39402. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  39403. */
  39404. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  39405. if ( rectangle !== null ) {
  39406. if ( rectangle.isVector2 ) {
  39407. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  39408. } else if ( rectangle.isVector4 ) {
  39409. rectangle = _vector4.copy( rectangle ).floor();
  39410. } else {
  39411. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  39412. return;
  39413. }
  39414. } else {
  39415. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  39416. }
  39417. //
  39418. let renderContext = this._currentRenderContext;
  39419. let renderTarget;
  39420. if ( renderContext !== null ) {
  39421. renderTarget = renderContext.renderTarget;
  39422. } else {
  39423. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  39424. if ( renderTarget !== null ) {
  39425. this._textures.updateRenderTarget( renderTarget );
  39426. renderContext = this._textures.get( renderTarget );
  39427. }
  39428. }
  39429. //
  39430. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  39431. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  39432. }
  39433. /**
  39434. * Copies data of the given source texture into a destination texture.
  39435. *
  39436. * @param {Texture} srcTexture - The source texture.
  39437. * @param {Texture} dstTexture - The destination texture.
  39438. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  39439. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  39440. * @param {number} [srcLevel=0] - The source mip level to copy from.
  39441. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  39442. */
  39443. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  39444. this._textures.updateTexture( srcTexture );
  39445. this._textures.updateTexture( dstTexture );
  39446. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  39447. }
  39448. /**
  39449. * Reads pixel data from the given render target.
  39450. *
  39451. * @async
  39452. * @param {RenderTarget} renderTarget - The render target to read from.
  39453. * @param {number} x - The `x` coordinate of the copy region's origin.
  39454. * @param {number} y - The `y` coordinate of the copy region's origin.
  39455. * @param {number} width - The width of the copy region.
  39456. * @param {number} height - The height of the copy region.
  39457. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  39458. * @param {number} [faceIndex=0] - The active cube face index.
  39459. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  39460. */
  39461. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  39462. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  39463. }
  39464. /**
  39465. * Analyzes the given 3D object's hierarchy and builds render lists from the
  39466. * processed hierarchy.
  39467. *
  39468. * @param {Object3D} object - The 3D object to process (usually a scene).
  39469. * @param {Camera} camera - The camera the object is rendered with.
  39470. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  39471. * @param {RenderList} renderList - The current render list.
  39472. * @param {ClippingContext} clippingContext - The current clipping context.
  39473. */
  39474. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  39475. if ( object.visible === false ) return;
  39476. const visible = object.layers.test( camera.layers );
  39477. if ( visible ) {
  39478. if ( object.isGroup ) {
  39479. groupOrder = object.renderOrder;
  39480. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  39481. } else if ( object.isLOD ) {
  39482. if ( object.autoUpdate === true ) object.update( camera );
  39483. } else if ( object.isLight ) {
  39484. renderList.pushLight( object );
  39485. } else if ( object.isSprite ) {
  39486. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  39487. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  39488. if ( this.sortObjects === true ) {
  39489. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  39490. }
  39491. const { geometry, material } = object;
  39492. if ( material.visible ) {
  39493. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  39494. }
  39495. }
  39496. } else if ( object.isLineLoop ) {
  39497. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  39498. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  39499. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  39500. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  39501. const { geometry, material } = object;
  39502. if ( this.sortObjects === true ) {
  39503. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  39504. _vector4
  39505. .copy( geometry.boundingSphere.center )
  39506. .applyMatrix4( object.matrixWorld )
  39507. .applyMatrix4( _projScreenMatrix );
  39508. }
  39509. if ( Array.isArray( material ) ) {
  39510. const groups = geometry.groups;
  39511. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  39512. const group = groups[ i ];
  39513. const groupMaterial = material[ group.materialIndex ];
  39514. if ( groupMaterial && groupMaterial.visible ) {
  39515. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  39516. }
  39517. }
  39518. } else if ( material.visible ) {
  39519. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  39520. }
  39521. }
  39522. }
  39523. }
  39524. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  39525. const baseRenderList = renderList;
  39526. // replace render list
  39527. renderList = this._renderLists.get( object, camera );
  39528. renderList.begin();
  39529. baseRenderList.pushBundle( {
  39530. bundleGroup: object,
  39531. camera,
  39532. renderList,
  39533. } );
  39534. renderList.finish();
  39535. }
  39536. const children = object.children;
  39537. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39538. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  39539. }
  39540. }
  39541. /**
  39542. * Renders the given render bundles.
  39543. *
  39544. * @private
  39545. * @param {Array<Object>} bundles - Array with render bundle data.
  39546. * @param {Scene} sceneRef - The scene the render bundles belong to.
  39547. * @param {LightsNode} lightsNode - The current lights node.
  39548. */
  39549. _renderBundles( bundles, sceneRef, lightsNode ) {
  39550. for ( const bundle of bundles ) {
  39551. this._renderBundle( bundle, sceneRef, lightsNode );
  39552. }
  39553. }
  39554. /**
  39555. * Renders the transparent objects from the given render lists.
  39556. *
  39557. * @private
  39558. * @param {Array<Object>} renderList - The transparent render list.
  39559. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  39560. * @param {Camera} camera - The camera the render list should be rendered with.
  39561. * @param {Scene} scene - The scene the render list belongs to.
  39562. * @param {LightsNode} lightsNode - The current lights node.
  39563. */
  39564. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  39565. if ( doublePassList.length > 0 ) {
  39566. // render back side
  39567. for ( const { material } of doublePassList ) {
  39568. material.side = BackSide;
  39569. }
  39570. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  39571. // render front side
  39572. for ( const { material } of doublePassList ) {
  39573. material.side = FrontSide;
  39574. }
  39575. this._renderObjects( renderList, camera, scene, lightsNode );
  39576. // restore
  39577. for ( const { material } of doublePassList ) {
  39578. material.side = DoubleSide;
  39579. }
  39580. } else {
  39581. this._renderObjects( renderList, camera, scene, lightsNode );
  39582. }
  39583. }
  39584. /**
  39585. * Renders the objects from the given render list.
  39586. *
  39587. * @private
  39588. * @param {Array<Object>} renderList - The render list.
  39589. * @param {Camera} camera - The camera the render list should be rendered with.
  39590. * @param {Scene} scene - The scene the render list belongs to.
  39591. * @param {LightsNode} lightsNode - The current lights node.
  39592. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  39593. */
  39594. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  39595. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  39596. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  39597. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  39598. }
  39599. }
  39600. /**
  39601. * This method represents the default render object function that manages the render lifecycle
  39602. * of the object.
  39603. *
  39604. * @param {Object3D} object - The 3D object.
  39605. * @param {Scene} scene - The scene the 3D object belongs to.
  39606. * @param {Camera} camera - The camera the object should be rendered with.
  39607. * @param {BufferGeometry} geometry - The object's geometry.
  39608. * @param {Material} material - The object's material.
  39609. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39610. * @param {LightsNode} lightsNode - The current lights node.
  39611. * @param {?ClippingContext} clippingContext - The clipping context.
  39612. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  39613. */
  39614. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  39615. let overridePositionNode;
  39616. let overrideColorNode;
  39617. let overrideDepthNode;
  39618. //
  39619. object.onBeforeRender( this, scene, camera, geometry, material, group );
  39620. //
  39621. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  39622. const overrideMaterial = scene.overrideMaterial;
  39623. if ( material.positionNode && material.positionNode.isNode ) {
  39624. overridePositionNode = overrideMaterial.positionNode;
  39625. overrideMaterial.positionNode = material.positionNode;
  39626. }
  39627. overrideMaterial.alphaTest = material.alphaTest;
  39628. overrideMaterial.alphaMap = material.alphaMap;
  39629. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  39630. if ( overrideMaterial.isShadowPassMaterial ) {
  39631. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  39632. if ( material.depthNode && material.depthNode.isNode ) {
  39633. overrideDepthNode = overrideMaterial.depthNode;
  39634. overrideMaterial.depthNode = material.depthNode;
  39635. }
  39636. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  39637. overrideColorNode = overrideMaterial.colorNode;
  39638. overrideMaterial.colorNode = material.castShadowNode;
  39639. }
  39640. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  39641. overridePositionNode = overrideMaterial.positionNode;
  39642. overrideMaterial.positionNode = material.castShadowPositionNode;
  39643. }
  39644. }
  39645. material = overrideMaterial;
  39646. }
  39647. //
  39648. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  39649. material.side = BackSide;
  39650. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  39651. material.side = FrontSide;
  39652. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  39653. material.side = DoubleSide;
  39654. } else {
  39655. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  39656. }
  39657. //
  39658. if ( overridePositionNode !== undefined ) {
  39659. scene.overrideMaterial.positionNode = overridePositionNode;
  39660. }
  39661. if ( overrideDepthNode !== undefined ) {
  39662. scene.overrideMaterial.depthNode = overrideDepthNode;
  39663. }
  39664. if ( overrideColorNode !== undefined ) {
  39665. scene.overrideMaterial.colorNode = overrideColorNode;
  39666. }
  39667. //
  39668. object.onAfterRender( this, scene, camera, geometry, material, group );
  39669. }
  39670. /**
  39671. * This method represents the default `_handleObjectFunction` implementation which creates
  39672. * a render object from the given data and performs the draw command with the selected backend.
  39673. *
  39674. * @private
  39675. * @param {Object3D} object - The 3D object.
  39676. * @param {Material} material - The object's material.
  39677. * @param {Scene} scene - The scene the 3D object belongs to.
  39678. * @param {Camera} camera - The camera the object should be rendered with.
  39679. * @param {LightsNode} lightsNode - The current lights node.
  39680. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39681. * @param {ClippingContext} clippingContext - The clipping context.
  39682. * @param {string} [passId] - An optional ID for identifying the pass.
  39683. */
  39684. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  39685. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  39686. renderObject.drawRange = object.geometry.drawRange;
  39687. renderObject.group = group;
  39688. //
  39689. const needsRefresh = this._nodes.needsRefresh( renderObject );
  39690. if ( needsRefresh ) {
  39691. this._nodes.updateBefore( renderObject );
  39692. this._geometries.updateForRender( renderObject );
  39693. this._nodes.updateForRender( renderObject );
  39694. this._bindings.updateForRender( renderObject );
  39695. }
  39696. this._pipelines.updateForRender( renderObject );
  39697. //
  39698. if ( this._currentRenderBundle !== null ) {
  39699. const renderBundleData = this.backend.get( this._currentRenderBundle );
  39700. renderBundleData.renderObjects.push( renderObject );
  39701. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  39702. }
  39703. this.backend.draw( renderObject, this.info );
  39704. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  39705. }
  39706. /**
  39707. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  39708. * Used in `compileAsync()`.
  39709. *
  39710. * @private
  39711. * @param {Object3D} object - The 3D object.
  39712. * @param {Material} material - The object's material.
  39713. * @param {Scene} scene - The scene the 3D object belongs to.
  39714. * @param {Camera} camera - The camera the object should be rendered with.
  39715. * @param {LightsNode} lightsNode - The current lights node.
  39716. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39717. * @param {ClippingContext} clippingContext - The clipping context.
  39718. * @param {string} [passId] - An optional ID for identifying the pass.
  39719. */
  39720. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  39721. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  39722. renderObject.drawRange = object.geometry.drawRange;
  39723. renderObject.group = group;
  39724. //
  39725. this._nodes.updateBefore( renderObject );
  39726. this._geometries.updateForRender( renderObject );
  39727. this._nodes.updateForRender( renderObject );
  39728. this._bindings.updateForRender( renderObject );
  39729. this._pipelines.getForRender( renderObject, this._compilationPromises );
  39730. this._nodes.updateAfter( renderObject );
  39731. }
  39732. /**
  39733. * Alias for `compileAsync()`.
  39734. *
  39735. * @method
  39736. * @param {Object3D} scene - The scene or 3D object to precompile.
  39737. * @param {Camera} camera - The camera that is used to render the scene.
  39738. * @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.
  39739. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  39740. */
  39741. get compile() {
  39742. return this.compileAsync;
  39743. }
  39744. }
  39745. /**
  39746. * A binding represents the connection between a resource (like a texture, sampler
  39747. * or uniform buffer) and the resource definition in a shader stage.
  39748. *
  39749. * This module is an abstract base class for all concrete bindings types.
  39750. *
  39751. * @abstract
  39752. * @private
  39753. */
  39754. class Binding {
  39755. /**
  39756. * Constructs a new binding.
  39757. *
  39758. * @param {string} [name=''] - The binding's name.
  39759. */
  39760. constructor( name = '' ) {
  39761. /**
  39762. * The binding's name.
  39763. *
  39764. * @type {string}
  39765. */
  39766. this.name = name;
  39767. /**
  39768. * A bitmask that defines in what shader stages the
  39769. * binding's resource is accessible.
  39770. *
  39771. * @type {number}
  39772. */
  39773. this.visibility = 0;
  39774. }
  39775. /**
  39776. * Makes sure binding's resource is visible for the given shader stage.
  39777. *
  39778. * @param {number} visibility - The shader stage.
  39779. */
  39780. setVisibility( visibility ) {
  39781. this.visibility |= visibility;
  39782. }
  39783. /**
  39784. * Clones the binding.
  39785. *
  39786. * @return {Binding} The cloned binding.
  39787. */
  39788. clone() {
  39789. return Object.assign( new this.constructor(), this );
  39790. }
  39791. }
  39792. /**
  39793. * This function is usually called with the length in bytes of an array buffer.
  39794. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  39795. *
  39796. * @function
  39797. * @param {number} floatLength - The buffer length.
  39798. * @return {number} The padded length.
  39799. */
  39800. function getFloatLength( floatLength ) {
  39801. // ensure chunk size alignment (STD140 layout)
  39802. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  39803. }
  39804. /**
  39805. * Represents a buffer binding type.
  39806. *
  39807. * @private
  39808. * @abstract
  39809. * @augments Binding
  39810. */
  39811. class Buffer extends Binding {
  39812. /**
  39813. * Constructs a new buffer.
  39814. *
  39815. * @param {string} name - The buffer's name.
  39816. * @param {TypedArray} [buffer=null] - The buffer.
  39817. */
  39818. constructor( name, buffer = null ) {
  39819. super( name );
  39820. /**
  39821. * This flag can be used for type testing.
  39822. *
  39823. * @type {boolean}
  39824. * @readonly
  39825. * @default true
  39826. */
  39827. this.isBuffer = true;
  39828. /**
  39829. * The bytes per element.
  39830. *
  39831. * @type {number}
  39832. */
  39833. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  39834. /**
  39835. * A reference to the internal buffer.
  39836. *
  39837. * @private
  39838. * @type {TypedArray}
  39839. */
  39840. this._buffer = buffer;
  39841. }
  39842. /**
  39843. * The buffer's byte length.
  39844. *
  39845. * @type {number}
  39846. * @readonly
  39847. */
  39848. get byteLength() {
  39849. return getFloatLength( this._buffer.byteLength );
  39850. }
  39851. /**
  39852. * A reference to the internal buffer.
  39853. *
  39854. * @type {Float32Array}
  39855. * @readonly
  39856. */
  39857. get buffer() {
  39858. return this._buffer;
  39859. }
  39860. /**
  39861. * Updates the binding.
  39862. *
  39863. * @return {boolean} Whether the buffer has been updated and must be
  39864. * uploaded to the GPU.
  39865. */
  39866. update() {
  39867. return true;
  39868. }
  39869. }
  39870. /**
  39871. * Represents a uniform buffer binding type.
  39872. *
  39873. * @private
  39874. * @augments Buffer
  39875. */
  39876. class UniformBuffer extends Buffer {
  39877. /**
  39878. * Constructs a new uniform buffer.
  39879. *
  39880. * @param {string} name - The buffer's name.
  39881. * @param {TypedArray} [buffer=null] - The buffer.
  39882. */
  39883. constructor( name, buffer = null ) {
  39884. super( name, buffer );
  39885. /**
  39886. * This flag can be used for type testing.
  39887. *
  39888. * @type {boolean}
  39889. * @readonly
  39890. * @default true
  39891. */
  39892. this.isUniformBuffer = true;
  39893. }
  39894. }
  39895. let _id$4 = 0;
  39896. /**
  39897. * A special form of uniform buffer binding type.
  39898. * It's buffer value is managed by a node object.
  39899. *
  39900. * @private
  39901. * @augments UniformBuffer
  39902. */
  39903. class NodeUniformBuffer extends UniformBuffer {
  39904. /**
  39905. * Constructs a new node-based uniform buffer.
  39906. *
  39907. * @param {BufferNode} nodeUniform - The uniform buffer node.
  39908. * @param {UniformGroupNode} groupNode - The uniform group node.
  39909. */
  39910. constructor( nodeUniform, groupNode ) {
  39911. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  39912. /**
  39913. * The uniform buffer node.
  39914. *
  39915. * @type {BufferNode}
  39916. */
  39917. this.nodeUniform = nodeUniform;
  39918. /**
  39919. * The uniform group node.
  39920. *
  39921. * @type {UniformGroupNode}
  39922. */
  39923. this.groupNode = groupNode;
  39924. }
  39925. /**
  39926. * The uniform buffer.
  39927. *
  39928. * @type {Float32Array}
  39929. */
  39930. get buffer() {
  39931. return this.nodeUniform.value;
  39932. }
  39933. }
  39934. /**
  39935. * This class represents a uniform buffer binding but with
  39936. * an API that allows to maintain individual uniform objects.
  39937. *
  39938. * @private
  39939. * @augments UniformBuffer
  39940. */
  39941. class UniformsGroup extends UniformBuffer {
  39942. /**
  39943. * Constructs a new uniforms group.
  39944. *
  39945. * @param {string} name - The group's name.
  39946. */
  39947. constructor( name ) {
  39948. super( name );
  39949. /**
  39950. * This flag can be used for type testing.
  39951. *
  39952. * @type {boolean}
  39953. * @readonly
  39954. * @default true
  39955. */
  39956. this.isUniformsGroup = true;
  39957. /**
  39958. * An array with the raw uniform values.
  39959. *
  39960. * @private
  39961. * @type {?Array<number>}
  39962. * @default null
  39963. */
  39964. this._values = null;
  39965. /**
  39966. * An array of uniform objects.
  39967. *
  39968. * The order of uniforms in this array must match the order of uniforms in the shader.
  39969. *
  39970. * @type {Array<Uniform>}
  39971. */
  39972. this.uniforms = [];
  39973. }
  39974. /**
  39975. * Adds a uniform to this group.
  39976. *
  39977. * @param {Uniform} uniform - The uniform to add.
  39978. * @return {UniformsGroup} A reference to this group.
  39979. */
  39980. addUniform( uniform ) {
  39981. this.uniforms.push( uniform );
  39982. return this;
  39983. }
  39984. /**
  39985. * Removes a uniform from this group.
  39986. *
  39987. * @param {Uniform} uniform - The uniform to remove.
  39988. * @return {UniformsGroup} A reference to this group.
  39989. */
  39990. removeUniform( uniform ) {
  39991. const index = this.uniforms.indexOf( uniform );
  39992. if ( index !== -1 ) {
  39993. this.uniforms.splice( index, 1 );
  39994. }
  39995. return this;
  39996. }
  39997. /**
  39998. * An array with the raw uniform values.
  39999. *
  40000. * @type {Array<number>}
  40001. */
  40002. get values() {
  40003. if ( this._values === null ) {
  40004. this._values = Array.from( this.buffer );
  40005. }
  40006. return this._values;
  40007. }
  40008. /**
  40009. * A Float32 array buffer with the uniform values.
  40010. *
  40011. * @type {Float32Array}
  40012. */
  40013. get buffer() {
  40014. let buffer = this._buffer;
  40015. if ( buffer === null ) {
  40016. const byteLength = this.byteLength;
  40017. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  40018. this._buffer = buffer;
  40019. }
  40020. return buffer;
  40021. }
  40022. /**
  40023. * The byte length of the buffer with correct buffer alignment.
  40024. *
  40025. * @type {number}
  40026. */
  40027. get byteLength() {
  40028. const bytesPerElement = this.bytesPerElement;
  40029. let offset = 0; // global buffer offset in bytes
  40030. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  40031. const uniform = this.uniforms[ i ];
  40032. const boundary = uniform.boundary;
  40033. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  40034. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  40035. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  40036. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  40037. offset += chunkPadding;
  40038. // Check for chunk overflow
  40039. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  40040. // Add padding to the end of the chunk
  40041. offset += ( GPU_CHUNK_BYTES - chunkStart );
  40042. }
  40043. uniform.offset = offset / bytesPerElement;
  40044. offset += itemSize;
  40045. }
  40046. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  40047. }
  40048. /**
  40049. * Updates this group by updating each uniform object of
  40050. * the internal uniform list. The uniform objects check if their
  40051. * values has actually changed so this method only returns
  40052. * `true` if there is a real value change.
  40053. *
  40054. * @return {boolean} Whether the uniforms have been updated and
  40055. * must be uploaded to the GPU.
  40056. */
  40057. update() {
  40058. let updated = false;
  40059. for ( const uniform of this.uniforms ) {
  40060. if ( this.updateByType( uniform ) === true ) {
  40061. updated = true;
  40062. }
  40063. }
  40064. return updated;
  40065. }
  40066. /**
  40067. * Updates a given uniform by calling an update method matching
  40068. * the uniforms type.
  40069. *
  40070. * @param {Uniform} uniform - The uniform to update.
  40071. * @return {boolean} Whether the uniform has been updated or not.
  40072. */
  40073. updateByType( uniform ) {
  40074. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  40075. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  40076. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  40077. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  40078. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  40079. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  40080. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  40081. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  40082. }
  40083. /**
  40084. * Updates a given Number uniform.
  40085. *
  40086. * @param {NumberUniform} uniform - The Number uniform.
  40087. * @return {boolean} Whether the uniform has been updated or not.
  40088. */
  40089. updateNumber( uniform ) {
  40090. let updated = false;
  40091. const a = this.values;
  40092. const v = uniform.getValue();
  40093. const offset = uniform.offset;
  40094. const type = uniform.getType();
  40095. if ( a[ offset ] !== v ) {
  40096. const b = this._getBufferForType( type );
  40097. b[ offset ] = a[ offset ] = v;
  40098. updated = true;
  40099. }
  40100. return updated;
  40101. }
  40102. /**
  40103. * Updates a given Vector2 uniform.
  40104. *
  40105. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  40106. * @return {boolean} Whether the uniform has been updated or not.
  40107. */
  40108. updateVector2( uniform ) {
  40109. let updated = false;
  40110. const a = this.values;
  40111. const v = uniform.getValue();
  40112. const offset = uniform.offset;
  40113. const type = uniform.getType();
  40114. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  40115. const b = this._getBufferForType( type );
  40116. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40117. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40118. updated = true;
  40119. }
  40120. return updated;
  40121. }
  40122. /**
  40123. * Updates a given Vector3 uniform.
  40124. *
  40125. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  40126. * @return {boolean} Whether the uniform has been updated or not.
  40127. */
  40128. updateVector3( uniform ) {
  40129. let updated = false;
  40130. const a = this.values;
  40131. const v = uniform.getValue();
  40132. const offset = uniform.offset;
  40133. const type = uniform.getType();
  40134. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  40135. const b = this._getBufferForType( type );
  40136. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40137. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40138. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  40139. updated = true;
  40140. }
  40141. return updated;
  40142. }
  40143. /**
  40144. * Updates a given Vector4 uniform.
  40145. *
  40146. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  40147. * @return {boolean} Whether the uniform has been updated or not.
  40148. */
  40149. updateVector4( uniform ) {
  40150. let updated = false;
  40151. const a = this.values;
  40152. const v = uniform.getValue();
  40153. const offset = uniform.offset;
  40154. const type = uniform.getType();
  40155. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  40156. const b = this._getBufferForType( type );
  40157. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40158. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40159. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  40160. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  40161. updated = true;
  40162. }
  40163. return updated;
  40164. }
  40165. /**
  40166. * Updates a given Color uniform.
  40167. *
  40168. * @param {ColorUniform} uniform - The Color uniform.
  40169. * @return {boolean} Whether the uniform has been updated or not.
  40170. */
  40171. updateColor( uniform ) {
  40172. let updated = false;
  40173. const a = this.values;
  40174. const c = uniform.getValue();
  40175. const offset = uniform.offset;
  40176. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  40177. const b = this.buffer;
  40178. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  40179. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  40180. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  40181. updated = true;
  40182. }
  40183. return updated;
  40184. }
  40185. /**
  40186. * Updates a given Matrix3 uniform.
  40187. *
  40188. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  40189. * @return {boolean} Whether the uniform has been updated or not.
  40190. */
  40191. updateMatrix3( uniform ) {
  40192. let updated = false;
  40193. const a = this.values;
  40194. const e = uniform.getValue().elements;
  40195. const offset = uniform.offset;
  40196. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  40197. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  40198. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  40199. const b = this.buffer;
  40200. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  40201. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  40202. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  40203. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  40204. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  40205. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  40206. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  40207. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  40208. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  40209. updated = true;
  40210. }
  40211. return updated;
  40212. }
  40213. /**
  40214. * Updates a given Matrix4 uniform.
  40215. *
  40216. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  40217. * @return {boolean} Whether the uniform has been updated or not.
  40218. */
  40219. updateMatrix4( uniform ) {
  40220. let updated = false;
  40221. const a = this.values;
  40222. const e = uniform.getValue().elements;
  40223. const offset = uniform.offset;
  40224. if ( arraysEqual( a, e, offset ) === false ) {
  40225. const b = this.buffer;
  40226. b.set( e, offset );
  40227. setArray( a, e, offset );
  40228. updated = true;
  40229. }
  40230. return updated;
  40231. }
  40232. /**
  40233. * Returns a typed array that matches the given data type.
  40234. *
  40235. * @param {string} type - The data type.
  40236. * @return {TypedArray} The typed array.
  40237. */
  40238. _getBufferForType( type ) {
  40239. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  40240. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  40241. return this.buffer;
  40242. }
  40243. }
  40244. /**
  40245. * Sets the values of the second array to the first array.
  40246. *
  40247. * @private
  40248. * @param {TypedArray} a - The first array.
  40249. * @param {TypedArray} b - The second array.
  40250. * @param {number} offset - An index offset for the first array.
  40251. */
  40252. function setArray( a, b, offset ) {
  40253. for ( let i = 0, l = b.length; i < l; i ++ ) {
  40254. a[ offset + i ] = b[ i ];
  40255. }
  40256. }
  40257. /**
  40258. * Returns `true` if the given arrays are equal.
  40259. *
  40260. * @private
  40261. * @param {TypedArray} a - The first array.
  40262. * @param {TypedArray} b - The second array.
  40263. * @param {number} offset - An index offset for the first array.
  40264. * @return {boolean} Whether the given arrays are equal or not.
  40265. */
  40266. function arraysEqual( a, b, offset ) {
  40267. for ( let i = 0, l = b.length; i < l; i ++ ) {
  40268. if ( a[ offset + i ] !== b[ i ] ) return false;
  40269. }
  40270. return true;
  40271. }
  40272. let _id$3 = 0;
  40273. /**
  40274. * A special form of uniforms group that represents
  40275. * the individual uniforms as node-based uniforms.
  40276. *
  40277. * @private
  40278. * @augments UniformsGroup
  40279. */
  40280. class NodeUniformsGroup extends UniformsGroup {
  40281. /**
  40282. * Constructs a new node-based uniforms group.
  40283. *
  40284. * @param {string} name - The group's name.
  40285. * @param {UniformGroupNode} groupNode - The uniform group node.
  40286. */
  40287. constructor( name, groupNode ) {
  40288. super( name );
  40289. /**
  40290. * The group's ID.
  40291. *
  40292. * @type {number}
  40293. */
  40294. this.id = _id$3 ++;
  40295. /**
  40296. * The uniform group node.
  40297. *
  40298. * @type {UniformGroupNode}
  40299. */
  40300. this.groupNode = groupNode;
  40301. /**
  40302. * This flag can be used for type testing.
  40303. *
  40304. * @type {boolean}
  40305. * @readonly
  40306. * @default true
  40307. */
  40308. this.isNodeUniformsGroup = true;
  40309. }
  40310. }
  40311. /**
  40312. * Represents a sampler binding type.
  40313. *
  40314. * @private
  40315. * @augments Binding
  40316. */
  40317. class Sampler extends Binding {
  40318. /**
  40319. * Constructs a new sampler.
  40320. *
  40321. * @param {string} name - The samplers's name.
  40322. * @param {?Texture} texture - The texture this binding is referring to.
  40323. */
  40324. constructor( name, texture ) {
  40325. super( name );
  40326. /**
  40327. * This function is called when the texture is disposed.
  40328. * @type {function}
  40329. * @private
  40330. */
  40331. this._onDisposeTexture = () => {
  40332. this.texture = null;
  40333. };
  40334. /**
  40335. * The texture the sampler is referring to.
  40336. *
  40337. * @type {?Texture}
  40338. */
  40339. this.texture = texture;
  40340. /**
  40341. * The binding's version.
  40342. *
  40343. * @type {number}
  40344. */
  40345. this.version = texture ? texture.version : 0;
  40346. /**
  40347. * The binding's generation which is an additional version
  40348. * qualifier.
  40349. *
  40350. * @type {?number}
  40351. * @default null
  40352. */
  40353. this.generation = null;
  40354. /**
  40355. * This flag can be used for type testing.
  40356. *
  40357. * @type {boolean}
  40358. * @readonly
  40359. * @default true
  40360. */
  40361. this.isSampler = true;
  40362. }
  40363. /**
  40364. * Sets the texture of this sampler.
  40365. * @param {?Texture} value - The texture to set.
  40366. */
  40367. set texture( value ) {
  40368. if ( this._texture === value ) return;
  40369. if ( this._texture ) {
  40370. this._texture.removeEventListener( 'dispose', this._onDisposeTexture );
  40371. }
  40372. this._texture = value;
  40373. this.generation = null;
  40374. this.version = 0;
  40375. if ( this._texture ) {
  40376. this._texture.addEventListener( 'dispose', this._onDisposeTexture );
  40377. }
  40378. }
  40379. /**
  40380. * Gets the texture of this sampler.
  40381. * @return {?Texture} The texture.
  40382. */
  40383. get texture() {
  40384. return this._texture;
  40385. }
  40386. /**
  40387. * Updates the binding.
  40388. *
  40389. * @return {boolean} Whether the texture has been updated and must be
  40390. * uploaded to the GPU.
  40391. */
  40392. update() {
  40393. const { texture, version } = this;
  40394. if ( version !== texture.version ) {
  40395. this.version = texture.version;
  40396. return true;
  40397. }
  40398. return false;
  40399. }
  40400. }
  40401. let _id$2 = 0;
  40402. /**
  40403. * Represents a sampled texture binding type.
  40404. *
  40405. * @private
  40406. * @augments Binding
  40407. */
  40408. class SampledTexture extends Sampler {
  40409. /**
  40410. * Constructs a new sampled texture.
  40411. *
  40412. * @param {string} name - The sampled texture's name.
  40413. * @param {?Texture} texture - The texture this binding is referring to.
  40414. */
  40415. constructor( name, texture ) {
  40416. super( name, texture );
  40417. /**
  40418. * This identifier.
  40419. *
  40420. * @type {number}
  40421. */
  40422. this.id = _id$2 ++;
  40423. /**
  40424. * Whether the texture is a storage texture or not.
  40425. *
  40426. * @type {boolean}
  40427. * @default false
  40428. */
  40429. this.store = false;
  40430. /**
  40431. * This flag can be used for type testing.
  40432. *
  40433. * @type {boolean}
  40434. * @readonly
  40435. * @default true
  40436. */
  40437. this.isSampledTexture = true;
  40438. }
  40439. }
  40440. /**
  40441. * A special form of sampled texture binding type.
  40442. * It's texture value is managed by a node object.
  40443. *
  40444. * @private
  40445. * @augments SampledTexture
  40446. */
  40447. class NodeSampledTexture extends SampledTexture {
  40448. /**
  40449. * Constructs a new node-based sampled texture.
  40450. *
  40451. * @param {string} name - The textures's name.
  40452. * @param {TextureNode} textureNode - The texture node.
  40453. * @param {UniformGroupNode} groupNode - The uniform group node.
  40454. * @param {?string} [access=null] - The access type.
  40455. */
  40456. constructor( name, textureNode, groupNode, access = null ) {
  40457. super( name, textureNode ? textureNode.value : null );
  40458. /**
  40459. * The texture node.
  40460. *
  40461. * @type {TextureNode}
  40462. */
  40463. this.textureNode = textureNode;
  40464. /**
  40465. * The uniform group node.
  40466. *
  40467. * @type {UniformGroupNode}
  40468. */
  40469. this.groupNode = groupNode;
  40470. /**
  40471. * The access type.
  40472. *
  40473. * @type {?string}
  40474. * @default null
  40475. */
  40476. this.access = access;
  40477. }
  40478. /**
  40479. * Updates the binding.
  40480. *
  40481. * @return {boolean} Whether the texture has been updated and must be
  40482. * uploaded to the GPU.
  40483. */
  40484. update() {
  40485. const { textureNode } = this;
  40486. if ( this.texture !== textureNode.value ) {
  40487. this.texture = textureNode.value;
  40488. return true;
  40489. }
  40490. return super.update();
  40491. }
  40492. }
  40493. /**
  40494. * A special form of sampled cube texture binding type.
  40495. * It's texture value is managed by a node object.
  40496. *
  40497. * @private
  40498. * @augments NodeSampledTexture
  40499. */
  40500. class NodeSampledCubeTexture extends NodeSampledTexture {
  40501. /**
  40502. * Constructs a new node-based sampled cube texture.
  40503. *
  40504. * @param {string} name - The textures's name.
  40505. * @param {TextureNode} textureNode - The texture node.
  40506. * @param {UniformGroupNode} groupNode - The uniform group node.
  40507. * @param {?string} [access=null] - The access type.
  40508. */
  40509. constructor( name, textureNode, groupNode, access = null ) {
  40510. super( name, textureNode, groupNode, access );
  40511. /**
  40512. * This flag can be used for type testing.
  40513. *
  40514. * @type {boolean}
  40515. * @readonly
  40516. * @default true
  40517. */
  40518. this.isSampledCubeTexture = true;
  40519. }
  40520. }
  40521. /**
  40522. * A special form of sampled 3D texture binding type.
  40523. * It's texture value is managed by a node object.
  40524. *
  40525. * @private
  40526. * @augments NodeSampledTexture
  40527. */
  40528. class NodeSampledTexture3D extends NodeSampledTexture {
  40529. /**
  40530. * Constructs a new node-based sampled 3D texture.
  40531. *
  40532. * @param {string} name - The textures's name.
  40533. * @param {TextureNode} textureNode - The texture node.
  40534. * @param {UniformGroupNode} groupNode - The uniform group node.
  40535. * @param {?string} [access=null] - The access type.
  40536. */
  40537. constructor( name, textureNode, groupNode, access = null ) {
  40538. super( name, textureNode, groupNode, access );
  40539. /**
  40540. * This flag can be used for type testing.
  40541. *
  40542. * @type {boolean}
  40543. * @readonly
  40544. * @default true
  40545. */
  40546. this.isSampledTexture3D = true;
  40547. }
  40548. }
  40549. const glslMethods = {
  40550. textureDimensions: 'textureSize',
  40551. equals: 'equal'
  40552. };
  40553. const precisionLib = {
  40554. low: 'lowp',
  40555. medium: 'mediump',
  40556. high: 'highp'
  40557. };
  40558. const supports$1 = {
  40559. swizzleAssign: true,
  40560. storageBuffer: false
  40561. };
  40562. const interpolationTypeMap = {
  40563. perspective: 'smooth',
  40564. linear: 'noperspective'
  40565. };
  40566. const interpolationModeMap = {
  40567. 'centroid': 'centroid'
  40568. };
  40569. const defaultPrecisions = `
  40570. precision highp float;
  40571. precision highp int;
  40572. precision highp sampler2D;
  40573. precision highp sampler3D;
  40574. precision highp samplerCube;
  40575. precision highp sampler2DArray;
  40576. precision highp usampler2D;
  40577. precision highp usampler3D;
  40578. precision highp usamplerCube;
  40579. precision highp usampler2DArray;
  40580. precision highp isampler2D;
  40581. precision highp isampler3D;
  40582. precision highp isamplerCube;
  40583. precision highp isampler2DArray;
  40584. precision lowp sampler2DShadow;
  40585. precision lowp sampler2DArrayShadow;
  40586. precision lowp samplerCubeShadow;
  40587. `;
  40588. /**
  40589. * A node builder targeting GLSL.
  40590. *
  40591. * This module generates GLSL shader code from node materials and also
  40592. * generates the respective bindings and vertex buffer definitions. These
  40593. * data are later used by the renderer to create render and compute pipelines
  40594. * for render objects.
  40595. *
  40596. * @augments NodeBuilder
  40597. */
  40598. class GLSLNodeBuilder extends NodeBuilder {
  40599. /**
  40600. * Constructs a new GLSL node builder renderer.
  40601. *
  40602. * @param {Object3D} object - The 3D object.
  40603. * @param {Renderer} renderer - The renderer.
  40604. */
  40605. constructor( object, renderer ) {
  40606. super( object, renderer, new GLSLNodeParser() );
  40607. /**
  40608. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  40609. * another dictionary which manages UBOs per group ('render','frame','object').
  40610. *
  40611. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  40612. */
  40613. this.uniformGroups = {};
  40614. /**
  40615. * An array that holds objects defining the varying and attribute data in
  40616. * context of Transform Feedback.
  40617. *
  40618. * @type {Array<Object<string,AttributeNode|string>>}
  40619. */
  40620. this.transforms = [];
  40621. /**
  40622. * A dictionary that holds for each shader stage a Map of used extensions.
  40623. *
  40624. * @type {Object<string,Map<string,Object>>}
  40625. */
  40626. this.extensions = {};
  40627. /**
  40628. * A dictionary that holds for each shader stage an Array of used builtins.
  40629. *
  40630. * @type {Object<string,Array<string>>}
  40631. */
  40632. this.builtins = { vertex: [], fragment: [], compute: [] };
  40633. }
  40634. /**
  40635. * Checks if the given texture requires a manual conversion to the working color space.
  40636. *
  40637. * @param {Texture} texture - The texture to check.
  40638. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  40639. */
  40640. needsToWorkingColorSpace( texture ) {
  40641. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  40642. }
  40643. /**
  40644. * Returns the native shader method name for a given generic name.
  40645. *
  40646. * @param {string} method - The method name to resolve.
  40647. * @return {string} The resolved GLSL method name.
  40648. */
  40649. getMethod( method ) {
  40650. return glslMethods[ method ] || method;
  40651. }
  40652. /**
  40653. * Returns the output struct name. Not relevant for GLSL.
  40654. *
  40655. * @return {string}
  40656. */
  40657. getOutputStructName() {
  40658. return '';
  40659. }
  40660. /**
  40661. * Builds the given shader node.
  40662. *
  40663. * @param {ShaderNodeInternal} shaderNode - The shader node.
  40664. * @return {string} The GLSL function code.
  40665. */
  40666. buildFunctionCode( shaderNode ) {
  40667. const layout = shaderNode.layout;
  40668. const flowData = this.flowShaderNode( shaderNode );
  40669. const parameters = [];
  40670. for ( const input of layout.inputs ) {
  40671. parameters.push( this.getType( input.type ) + ' ' + input.name );
  40672. }
  40673. //
  40674. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  40675. ${ flowData.vars }
  40676. ${ flowData.code }
  40677. return ${ flowData.result };
  40678. }`;
  40679. //
  40680. return code;
  40681. }
  40682. /**
  40683. * Setups the Pixel Buffer Object (PBO) for the given storage
  40684. * buffer node.
  40685. *
  40686. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  40687. */
  40688. setupPBO( storageBufferNode ) {
  40689. const attribute = storageBufferNode.value;
  40690. if ( attribute.pbo === undefined ) {
  40691. const originalArray = attribute.array;
  40692. const numElements = attribute.count * attribute.itemSize;
  40693. const { itemSize } = attribute;
  40694. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  40695. let format = isInteger ? RedIntegerFormat : RedFormat;
  40696. if ( itemSize === 2 ) {
  40697. format = isInteger ? RGIntegerFormat : RGFormat;
  40698. } else if ( itemSize === 3 ) {
  40699. format = isInteger ? RGBIntegerFormat : RGBFormat;
  40700. } else if ( itemSize === 4 ) {
  40701. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  40702. }
  40703. const typeMap = {
  40704. Float32Array: FloatType,
  40705. Uint8Array: UnsignedByteType,
  40706. Uint16Array: UnsignedShortType,
  40707. Uint32Array: UnsignedIntType,
  40708. Int8Array: ByteType,
  40709. Int16Array: ShortType,
  40710. Int32Array: IntType,
  40711. Uint8ClampedArray: UnsignedByteType,
  40712. };
  40713. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  40714. let height = Math.ceil( ( numElements / itemSize ) / width );
  40715. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  40716. const newSize = width * height * itemSize;
  40717. const newArray = new originalArray.constructor( newSize );
  40718. newArray.set( originalArray, 0 );
  40719. attribute.array = newArray;
  40720. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  40721. pboTexture.needsUpdate = true;
  40722. pboTexture.isPBOTexture = true;
  40723. const pbo = new TextureNode( pboTexture, null, null );
  40724. pbo.setPrecision( 'high' );
  40725. attribute.pboNode = pbo;
  40726. attribute.pbo = pbo.value;
  40727. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  40728. }
  40729. }
  40730. /**
  40731. * Returns a GLSL snippet that represents the property name of the given node.
  40732. *
  40733. * @param {Node} node - The node.
  40734. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  40735. * @return {string} The property name.
  40736. */
  40737. getPropertyName( node, shaderStage = this.shaderStage ) {
  40738. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  40739. return shaderStage.charAt( 0 ) + '_' + node.name;
  40740. }
  40741. return super.getPropertyName( node, shaderStage );
  40742. }
  40743. /**
  40744. * Setups the Pixel Buffer Object (PBO) for the given storage
  40745. * buffer node.
  40746. *
  40747. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  40748. * @return {string} The property name.
  40749. */
  40750. generatePBO( storageArrayElementNode ) {
  40751. const { node, indexNode } = storageArrayElementNode;
  40752. const attribute = node.value;
  40753. if ( this.renderer.backend.has( attribute ) ) {
  40754. const attributeData = this.renderer.backend.get( attribute );
  40755. attributeData.pbo = attribute.pbo;
  40756. }
  40757. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  40758. const textureName = this.getPropertyName( nodeUniform );
  40759. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  40760. const indexSnippet = indexNode.build( this, 'uint' );
  40761. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  40762. let propertyName = elementNodeData.propertyName;
  40763. if ( propertyName === undefined ) {
  40764. // property element
  40765. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  40766. propertyName = this.getPropertyName( nodeVar );
  40767. // property size
  40768. const bufferNodeData = this.getDataFromNode( node );
  40769. let propertySizeName = bufferNodeData.propertySizeName;
  40770. if ( propertySizeName === undefined ) {
  40771. propertySizeName = propertyName + 'Size';
  40772. this.getVarFromNode( node, propertySizeName, 'uint' );
  40773. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  40774. bufferNodeData.propertySizeName = propertySizeName;
  40775. }
  40776. //
  40777. const { itemSize } = attribute;
  40778. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  40779. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  40780. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  40781. //
  40782. let prefix = 'vec4';
  40783. if ( attribute.pbo.type === UnsignedIntType ) {
  40784. prefix = 'uvec4';
  40785. } else if ( attribute.pbo.type === IntType ) {
  40786. prefix = 'ivec4';
  40787. }
  40788. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  40789. elementNodeData.propertyName = propertyName;
  40790. }
  40791. return propertyName;
  40792. }
  40793. /**
  40794. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  40795. *
  40796. * @param {Texture} texture - The texture.
  40797. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40798. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40799. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  40800. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  40801. * @return {string} The GLSL snippet.
  40802. */
  40803. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  40804. if ( depthSnippet ) {
  40805. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  40806. } else {
  40807. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  40808. }
  40809. }
  40810. /**
  40811. * Generates the GLSL snippet for sampling/loading the given texture.
  40812. *
  40813. * @param {Texture} texture - The texture.
  40814. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40815. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40816. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  40817. * @return {string} The GLSL snippet.
  40818. */
  40819. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  40820. if ( texture.isDepthTexture ) {
  40821. if ( depthSnippet ) uvSnippet = `vec4( ${ uvSnippet }, ${ depthSnippet } )`;
  40822. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  40823. } else {
  40824. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  40825. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  40826. }
  40827. }
  40828. /**
  40829. * Generates the GLSL snippet when sampling textures with explicit mip level.
  40830. *
  40831. * @param {Texture} texture - The texture.
  40832. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40833. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40834. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  40835. * @return {string} The GLSL snippet.
  40836. */
  40837. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  40838. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  40839. }
  40840. /**
  40841. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  40842. *
  40843. * @param {Texture} texture - The texture.
  40844. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40845. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40846. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  40847. * @return {string} The GLSL snippet.
  40848. */
  40849. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  40850. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  40851. }
  40852. /**
  40853. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  40854. *
  40855. * @param {Texture} texture - The texture.
  40856. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40857. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40858. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  40859. * @return {string} The GLSL snippet.
  40860. */
  40861. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  40862. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  40863. }
  40864. /**
  40865. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  40866. * against a reference value.
  40867. *
  40868. * @param {Texture} texture - The texture.
  40869. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40870. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40871. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  40872. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  40873. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  40874. * @return {string} The GLSL snippet.
  40875. */
  40876. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40877. if ( shaderStage === 'fragment' ) {
  40878. if ( depthSnippet ) {
  40879. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  40880. }
  40881. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  40882. } else {
  40883. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  40884. }
  40885. }
  40886. /**
  40887. * Returns the variables of the given shader stage as a GLSL string.
  40888. *
  40889. * @param {string} shaderStage - The shader stage.
  40890. * @return {string} The GLSL snippet that defines the variables.
  40891. */
  40892. getVars( shaderStage ) {
  40893. const snippets = [];
  40894. const vars = this.vars[ shaderStage ];
  40895. if ( vars !== undefined ) {
  40896. for ( const variable of vars ) {
  40897. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  40898. }
  40899. }
  40900. return snippets.join( '\n\t' );
  40901. }
  40902. /**
  40903. * Returns the uniforms of the given shader stage as a GLSL string.
  40904. *
  40905. * @param {string} shaderStage - The shader stage.
  40906. * @return {string} The GLSL snippet that defines the uniforms.
  40907. */
  40908. getUniforms( shaderStage ) {
  40909. const uniforms = this.uniforms[ shaderStage ];
  40910. const bindingSnippets = [];
  40911. const uniformGroups = {};
  40912. for ( const uniform of uniforms ) {
  40913. let snippet = null;
  40914. let group = false;
  40915. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  40916. const texture = uniform.node.value;
  40917. let typePrefix = '';
  40918. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  40919. if ( texture.type === UnsignedIntType ) {
  40920. typePrefix = 'u';
  40921. } else if ( texture.type === IntType ) {
  40922. typePrefix = 'i';
  40923. }
  40924. }
  40925. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  40926. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  40927. } else if ( texture.compareFunction ) {
  40928. if ( texture.isArrayTexture === true ) {
  40929. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  40930. } else {
  40931. snippet = `sampler2DShadow ${ uniform.name };`;
  40932. }
  40933. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40934. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  40935. } else {
  40936. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  40937. }
  40938. } else if ( uniform.type === 'cubeTexture' ) {
  40939. snippet = `samplerCube ${ uniform.name };`;
  40940. } else if ( uniform.type === 'buffer' ) {
  40941. const bufferNode = uniform.node;
  40942. const bufferType = this.getType( bufferNode.bufferType );
  40943. const bufferCount = bufferNode.bufferCount;
  40944. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  40945. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  40946. } else {
  40947. const vectorType = this.getVectorType( uniform.type );
  40948. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  40949. group = true;
  40950. }
  40951. const precision = uniform.node.precision;
  40952. if ( precision !== null ) {
  40953. snippet = precisionLib[ precision ] + ' ' + snippet;
  40954. }
  40955. if ( group ) {
  40956. snippet = '\t' + snippet;
  40957. const groupName = uniform.groupNode.name;
  40958. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  40959. groupSnippets.push( snippet );
  40960. } else {
  40961. snippet = 'uniform ' + snippet;
  40962. bindingSnippets.push( snippet );
  40963. }
  40964. }
  40965. let output = '';
  40966. for ( const name in uniformGroups ) {
  40967. const groupSnippets = uniformGroups[ name ];
  40968. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  40969. }
  40970. output += bindingSnippets.join( '\n' );
  40971. return output;
  40972. }
  40973. /**
  40974. * Returns the type for a given buffer attribute.
  40975. *
  40976. * @param {BufferAttribute} attribute - The buffer attribute.
  40977. * @return {string} The type.
  40978. */
  40979. getTypeFromAttribute( attribute ) {
  40980. let nodeType = super.getTypeFromAttribute( attribute );
  40981. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  40982. let dataAttribute = attribute;
  40983. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  40984. const array = dataAttribute.array;
  40985. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  40986. nodeType = nodeType.slice( 1 );
  40987. }
  40988. }
  40989. return nodeType;
  40990. }
  40991. /**
  40992. * Returns the shader attributes of the given shader stage as a GLSL string.
  40993. *
  40994. * @param {string} shaderStage - The shader stage.
  40995. * @return {string} The GLSL snippet that defines the shader attributes.
  40996. */
  40997. getAttributes( shaderStage ) {
  40998. let snippet = '';
  40999. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41000. const attributes = this.getAttributesArray();
  41001. let location = 0;
  41002. for ( const attribute of attributes ) {
  41003. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  41004. }
  41005. }
  41006. return snippet;
  41007. }
  41008. /**
  41009. * Returns the members of the given struct type node as a GLSL string.
  41010. *
  41011. * @param {StructTypeNode} struct - The struct type node.
  41012. * @return {string} The GLSL snippet that defines the struct members.
  41013. */
  41014. getStructMembers( struct ) {
  41015. const snippets = [];
  41016. for ( const member of struct.members ) {
  41017. snippets.push( `\t${ member.type } ${ member.name };` );
  41018. }
  41019. return snippets.join( '\n' );
  41020. }
  41021. /**
  41022. * Returns the structs of the given shader stage as a GLSL string.
  41023. *
  41024. * @param {string} shaderStage - The shader stage.
  41025. * @return {string} The GLSL snippet that defines the structs.
  41026. */
  41027. getStructs( shaderStage ) {
  41028. const snippets = [];
  41029. const structs = this.structs[ shaderStage ];
  41030. const outputSnippet = [];
  41031. for ( const struct of structs ) {
  41032. if ( struct.output ) {
  41033. for ( const member of struct.members ) {
  41034. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  41035. }
  41036. } else {
  41037. let snippet = 'struct ' + struct.name + ' {\n';
  41038. snippet += this.getStructMembers( struct );
  41039. snippet += '\n};\n';
  41040. snippets.push( snippet );
  41041. }
  41042. }
  41043. if ( outputSnippet.length === 0 ) {
  41044. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  41045. }
  41046. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  41047. }
  41048. /**
  41049. * Returns the varyings of the given shader stage as a GLSL string.
  41050. *
  41051. * @param {string} shaderStage - The shader stage.
  41052. * @return {string} The GLSL snippet that defines the varyings.
  41053. */
  41054. getVaryings( shaderStage ) {
  41055. let snippet = '';
  41056. const varyings = this.varyings;
  41057. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41058. for ( const varying of varyings ) {
  41059. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  41060. const type = this.getType( varying.type );
  41061. if ( varying.needsInterpolation ) {
  41062. if ( varying.interpolationType ) {
  41063. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  41064. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  41065. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  41066. } else {
  41067. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  41068. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  41069. }
  41070. } else {
  41071. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  41072. }
  41073. }
  41074. } else if ( shaderStage === 'fragment' ) {
  41075. for ( const varying of varyings ) {
  41076. if ( varying.needsInterpolation ) {
  41077. const type = this.getType( varying.type );
  41078. if ( varying.interpolationType ) {
  41079. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  41080. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  41081. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  41082. } else {
  41083. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  41084. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  41085. }
  41086. }
  41087. }
  41088. }
  41089. for ( const builtin of this.builtins[ shaderStage ] ) {
  41090. snippet += `${builtin};\n`;
  41091. }
  41092. return snippet;
  41093. }
  41094. /**
  41095. * Returns the vertex index builtin.
  41096. *
  41097. * @return {string} The vertex index.
  41098. */
  41099. getVertexIndex() {
  41100. return 'uint( gl_VertexID )';
  41101. }
  41102. /**
  41103. * Returns the instance index builtin.
  41104. *
  41105. * @return {string} The instance index.
  41106. */
  41107. getInstanceIndex() {
  41108. return 'uint( gl_InstanceID )';
  41109. }
  41110. /**
  41111. * Returns the invocation local index builtin.
  41112. *
  41113. * @return {string} The invocation local index.
  41114. */
  41115. getInvocationLocalIndex() {
  41116. const workgroupSize = this.object.workgroupSize;
  41117. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  41118. return `uint( gl_InstanceID ) % ${size}u`;
  41119. }
  41120. /**
  41121. * Returns the draw index builtin.
  41122. *
  41123. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  41124. */
  41125. getDrawIndex() {
  41126. const extensions = this.renderer.backend.extensions;
  41127. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  41128. return 'uint( gl_DrawID )';
  41129. }
  41130. return null;
  41131. }
  41132. /**
  41133. * Returns the front facing builtin.
  41134. *
  41135. * @return {string} The front facing builtin.
  41136. */
  41137. getFrontFacing() {
  41138. return 'gl_FrontFacing';
  41139. }
  41140. /**
  41141. * Returns the frag coord builtin.
  41142. *
  41143. * @return {string} The frag coord builtin.
  41144. */
  41145. getFragCoord() {
  41146. return 'gl_FragCoord.xy';
  41147. }
  41148. /**
  41149. * Returns the frag depth builtin.
  41150. *
  41151. * @return {string} The frag depth builtin.
  41152. */
  41153. getFragDepth() {
  41154. return 'gl_FragDepth';
  41155. }
  41156. /**
  41157. * Enables the given extension.
  41158. *
  41159. * @param {string} name - The extension name.
  41160. * @param {string} behavior - The extension behavior.
  41161. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  41162. */
  41163. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  41164. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  41165. if ( map.has( name ) === false ) {
  41166. map.set( name, {
  41167. name,
  41168. behavior
  41169. } );
  41170. }
  41171. }
  41172. /**
  41173. * Returns the enabled extensions of the given shader stage as a GLSL string.
  41174. *
  41175. * @param {string} shaderStage - The shader stage.
  41176. * @return {string} The GLSL snippet that defines the enabled extensions.
  41177. */
  41178. getExtensions( shaderStage ) {
  41179. const snippets = [];
  41180. if ( shaderStage === 'vertex' ) {
  41181. const ext = this.renderer.backend.extensions;
  41182. const isBatchedMesh = this.object.isBatchedMesh;
  41183. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  41184. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  41185. }
  41186. }
  41187. const extensions = this.extensions[ shaderStage ];
  41188. if ( extensions !== undefined ) {
  41189. for ( const { name, behavior } of extensions.values() ) {
  41190. snippets.push( `#extension ${name} : ${behavior}` );
  41191. }
  41192. }
  41193. return snippets.join( '\n' );
  41194. }
  41195. /**
  41196. * Returns the clip distances builtin.
  41197. *
  41198. * @return {string} The clip distances builtin.
  41199. */
  41200. getClipDistance() {
  41201. return 'gl_ClipDistance';
  41202. }
  41203. /**
  41204. * Whether the requested feature is available or not.
  41205. *
  41206. * @param {string} name - The requested feature.
  41207. * @return {boolean} Whether the requested feature is supported or not.
  41208. */
  41209. isAvailable( name ) {
  41210. let result = supports$1[ name ];
  41211. if ( result === undefined ) {
  41212. let extensionName;
  41213. result = false;
  41214. switch ( name ) {
  41215. case 'float32Filterable':
  41216. extensionName = 'OES_texture_float_linear';
  41217. break;
  41218. case 'clipDistance':
  41219. extensionName = 'WEBGL_clip_cull_distance';
  41220. break;
  41221. }
  41222. if ( extensionName !== undefined ) {
  41223. const extensions = this.renderer.backend.extensions;
  41224. if ( extensions.has( extensionName ) ) {
  41225. extensions.get( extensionName );
  41226. result = true;
  41227. }
  41228. }
  41229. supports$1[ name ] = result;
  41230. }
  41231. return result;
  41232. }
  41233. /**
  41234. * Whether to flip texture data along its vertical axis or not.
  41235. *
  41236. * @return {boolean} Returns always `true` in context of GLSL.
  41237. */
  41238. isFlipY() {
  41239. return true;
  41240. }
  41241. /**
  41242. * Enables hardware clipping.
  41243. *
  41244. * @param {string} planeCount - The clipping plane count.
  41245. */
  41246. enableHardwareClipping( planeCount ) {
  41247. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  41248. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  41249. }
  41250. /**
  41251. * Enables multiview.
  41252. */
  41253. enableMultiview() {
  41254. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  41255. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  41256. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  41257. }
  41258. /**
  41259. * Registers a transform in context of Transform Feedback.
  41260. *
  41261. * @param {string} varyingName - The varying name.
  41262. * @param {AttributeNode} attributeNode - The attribute node.
  41263. */
  41264. registerTransform( varyingName, attributeNode ) {
  41265. this.transforms.push( { varyingName, attributeNode } );
  41266. }
  41267. /**
  41268. * Returns the transforms of the given shader stage as a GLSL string.
  41269. *
  41270. * @param {string} shaderStage - The shader stage.
  41271. * @return {string} The GLSL snippet that defines the transforms.
  41272. */
  41273. getTransforms( /* shaderStage */ ) {
  41274. const transforms = this.transforms;
  41275. let snippet = '';
  41276. for ( let i = 0; i < transforms.length; i ++ ) {
  41277. const transform = transforms[ i ];
  41278. const attributeName = this.getPropertyName( transform.attributeNode );
  41279. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  41280. }
  41281. return snippet;
  41282. }
  41283. /**
  41284. * Returns a GLSL struct based on the given name and variables.
  41285. *
  41286. * @private
  41287. * @param {string} name - The struct name.
  41288. * @param {string} vars - The struct variables.
  41289. * @return {string} The GLSL snippet representing a struct.
  41290. */
  41291. _getGLSLUniformStruct( name, vars ) {
  41292. return `
  41293. layout( std140 ) uniform ${name} {
  41294. ${vars}
  41295. };`;
  41296. }
  41297. /**
  41298. * Returns a GLSL vertex shader based on the given shader data.
  41299. *
  41300. * @private
  41301. * @param {Object} shaderData - The shader data.
  41302. * @return {string} The vertex shader.
  41303. */
  41304. _getGLSLVertexCode( shaderData ) {
  41305. return `#version 300 es
  41306. ${ this.getSignature() }
  41307. // extensions
  41308. ${shaderData.extensions}
  41309. // precision
  41310. ${ defaultPrecisions }
  41311. // uniforms
  41312. ${shaderData.uniforms}
  41313. // varyings
  41314. ${shaderData.varyings}
  41315. // attributes
  41316. ${shaderData.attributes}
  41317. // codes
  41318. ${shaderData.codes}
  41319. void main() {
  41320. // vars
  41321. ${shaderData.vars}
  41322. // transforms
  41323. ${shaderData.transforms}
  41324. // flow
  41325. ${shaderData.flow}
  41326. gl_PointSize = 1.0;
  41327. }
  41328. `;
  41329. }
  41330. /**
  41331. * Returns a GLSL fragment shader based on the given shader data.
  41332. *
  41333. * @private
  41334. * @param {Object} shaderData - The shader data.
  41335. * @return {string} The vertex shader.
  41336. */
  41337. _getGLSLFragmentCode( shaderData ) {
  41338. return `#version 300 es
  41339. ${ this.getSignature() }
  41340. // extensions
  41341. ${shaderData.extensions}
  41342. // precision
  41343. ${ defaultPrecisions }
  41344. // uniforms
  41345. ${shaderData.uniforms}
  41346. // varyings
  41347. ${shaderData.varyings}
  41348. // codes
  41349. ${shaderData.codes}
  41350. // structs
  41351. ${shaderData.structs}
  41352. void main() {
  41353. // vars
  41354. ${shaderData.vars}
  41355. // flow
  41356. ${shaderData.flow}
  41357. }
  41358. `;
  41359. }
  41360. /**
  41361. * Controls the code build of the shader stages.
  41362. */
  41363. buildCode() {
  41364. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  41365. this.sortBindingGroups();
  41366. for ( const shaderStage in shadersData ) {
  41367. let flow = '// code\n\n';
  41368. flow += this.flowCode[ shaderStage ];
  41369. const flowNodes = this.flowNodes[ shaderStage ];
  41370. const mainNode = flowNodes[ flowNodes.length - 1 ];
  41371. for ( const node of flowNodes ) {
  41372. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  41373. const slotName = node.name;
  41374. if ( slotName ) {
  41375. if ( flow.length > 0 ) flow += '\n';
  41376. flow += `\t// flow -> ${ slotName }\n\t`;
  41377. }
  41378. flow += `${ flowSlotData.code }\n\t`;
  41379. if ( node === mainNode && shaderStage !== 'compute' ) {
  41380. flow += '// result\n\t';
  41381. if ( shaderStage === 'vertex' ) {
  41382. flow += 'gl_Position = ';
  41383. flow += `${ flowSlotData.result };`;
  41384. } else if ( shaderStage === 'fragment' ) {
  41385. if ( ! node.outputNode.isOutputStructNode ) {
  41386. flow += 'fragColor = ';
  41387. flow += `${ flowSlotData.result };`;
  41388. }
  41389. }
  41390. }
  41391. }
  41392. const stageData = shadersData[ shaderStage ];
  41393. stageData.extensions = this.getExtensions( shaderStage );
  41394. stageData.uniforms = this.getUniforms( shaderStage );
  41395. stageData.attributes = this.getAttributes( shaderStage );
  41396. stageData.varyings = this.getVaryings( shaderStage );
  41397. stageData.vars = this.getVars( shaderStage );
  41398. stageData.structs = this.getStructs( shaderStage );
  41399. stageData.codes = this.getCodes( shaderStage );
  41400. stageData.transforms = this.getTransforms( shaderStage );
  41401. stageData.flow = flow;
  41402. }
  41403. if ( this.material !== null ) {
  41404. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  41405. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  41406. } else {
  41407. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  41408. }
  41409. }
  41410. /**
  41411. * This method is one of the more important ones since it's responsible
  41412. * for generating a matching binding instance for the given uniform node.
  41413. *
  41414. * These bindings are later used in the renderer to create bind groups
  41415. * and layouts.
  41416. *
  41417. * @param {UniformNode} node - The uniform node.
  41418. * @param {string} type - The node data type.
  41419. * @param {string} shaderStage - The shader stage.
  41420. * @param {?string} [name=null] - An optional uniform name.
  41421. * @return {NodeUniform} The node uniform object.
  41422. */
  41423. getUniformFromNode( node, type, shaderStage, name = null ) {
  41424. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  41425. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  41426. let uniformGPU = nodeData.uniformGPU;
  41427. if ( uniformGPU === undefined ) {
  41428. const group = node.groupNode;
  41429. const groupName = group.name;
  41430. const bindings = this.getBindGroupArray( groupName, shaderStage );
  41431. if ( type === 'texture' ) {
  41432. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  41433. bindings.push( uniformGPU );
  41434. } else if ( type === 'cubeTexture' ) {
  41435. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  41436. bindings.push( uniformGPU );
  41437. } else if ( type === 'texture3D' ) {
  41438. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  41439. bindings.push( uniformGPU );
  41440. } else if ( type === 'buffer' ) {
  41441. node.name = `NodeBuffer_${ node.id }`;
  41442. uniformNode.name = `buffer${ node.id }`;
  41443. const buffer = new NodeUniformBuffer( node, group );
  41444. buffer.name = node.name;
  41445. bindings.push( buffer );
  41446. uniformGPU = buffer;
  41447. } else {
  41448. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  41449. let uniformsGroup = uniformsStage[ groupName ];
  41450. if ( uniformsGroup === undefined ) {
  41451. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  41452. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41453. uniformsStage[ groupName ] = uniformsGroup;
  41454. bindings.push( uniformsGroup );
  41455. }
  41456. uniformGPU = this.getNodeUniform( uniformNode, type );
  41457. uniformsGroup.addUniform( uniformGPU );
  41458. }
  41459. nodeData.uniformGPU = uniformGPU;
  41460. }
  41461. return uniformNode;
  41462. }
  41463. }
  41464. let _vector2 = null;
  41465. let _color4 = null;
  41466. /**
  41467. * Most of the rendering related logic is implemented in the
  41468. * {@link Renderer} module and related management components.
  41469. * Sometimes it is required though to execute commands which are
  41470. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  41471. * This abstract base class defines an interface that encapsulates
  41472. * all backend-related logic. Derived classes for each backend must
  41473. * implement the interface.
  41474. *
  41475. * @abstract
  41476. * @private
  41477. */
  41478. class Backend {
  41479. /**
  41480. * Constructs a new backend.
  41481. *
  41482. * @param {Object} parameters - An object holding parameters for the backend.
  41483. */
  41484. constructor( parameters = {} ) {
  41485. /**
  41486. * The parameters of the backend.
  41487. *
  41488. * @type {Object}
  41489. */
  41490. this.parameters = Object.assign( {}, parameters );
  41491. /**
  41492. * This weak map holds backend-specific data of objects
  41493. * like textures, attributes or render targets.
  41494. *
  41495. * @type {WeakMap}
  41496. */
  41497. this.data = new WeakMap();
  41498. /**
  41499. * A reference to the renderer.
  41500. *
  41501. * @type {?Renderer}
  41502. * @default null
  41503. */
  41504. this.renderer = null;
  41505. /**
  41506. * A reference to the canvas element the renderer is drawing to.
  41507. *
  41508. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  41509. * @default null
  41510. */
  41511. this.domElement = null;
  41512. /**
  41513. * A reference to the timestamp query pool.
  41514. *
  41515. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  41516. */
  41517. this.timestampQueryPool = {
  41518. 'render': null,
  41519. 'compute': null
  41520. };
  41521. /**
  41522. * Whether to track timestamps with a Timestamp Query API or not.
  41523. *
  41524. * @type {boolean}
  41525. * @default false
  41526. */
  41527. this.trackTimestamp = ( parameters.trackTimestamp === true );
  41528. }
  41529. /**
  41530. * Initializes the backend so it is ready for usage. Concrete backends
  41531. * are supposed to implement their rendering context creation and related
  41532. * operations in this method.
  41533. *
  41534. * @async
  41535. * @param {Renderer} renderer - The renderer.
  41536. * @return {Promise} A Promise that resolves when the backend has been initialized.
  41537. */
  41538. async init( renderer ) {
  41539. this.renderer = renderer;
  41540. }
  41541. /**
  41542. * The coordinate system of the backend.
  41543. *
  41544. * @abstract
  41545. * @type {number}
  41546. * @readonly
  41547. */
  41548. get coordinateSystem() {}
  41549. // render context
  41550. /**
  41551. * This method is executed at the beginning of a render call and
  41552. * can be used by the backend to prepare the state for upcoming
  41553. * draw calls.
  41554. *
  41555. * @abstract
  41556. * @param {RenderContext} renderContext - The render context.
  41557. */
  41558. beginRender( /*renderContext*/ ) {}
  41559. /**
  41560. * This method is executed at the end of a render call and
  41561. * can be used by the backend to finalize work after draw
  41562. * calls.
  41563. *
  41564. * @abstract
  41565. * @param {RenderContext} renderContext - The render context.
  41566. */
  41567. finishRender( /*renderContext*/ ) {}
  41568. /**
  41569. * This method is executed at the beginning of a compute call and
  41570. * can be used by the backend to prepare the state for upcoming
  41571. * compute tasks.
  41572. *
  41573. * @abstract
  41574. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41575. */
  41576. beginCompute( /*computeGroup*/ ) {}
  41577. /**
  41578. * This method is executed at the end of a compute call and
  41579. * can be used by the backend to finalize work after compute
  41580. * tasks.
  41581. *
  41582. * @abstract
  41583. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41584. */
  41585. finishCompute( /*computeGroup*/ ) {}
  41586. // render object
  41587. /**
  41588. * Executes a draw command for the given render object.
  41589. *
  41590. * @abstract
  41591. * @param {RenderObject} renderObject - The render object to draw.
  41592. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  41593. */
  41594. draw( /*renderObject, info*/ ) { }
  41595. // compute node
  41596. /**
  41597. * Executes a compute command for the given compute node.
  41598. *
  41599. * @abstract
  41600. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  41601. * @param {Node} computeNode - The compute node.
  41602. * @param {Array<BindGroup>} bindings - The bindings.
  41603. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41604. */
  41605. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  41606. // program
  41607. /**
  41608. * Creates a shader program from the given programmable stage.
  41609. *
  41610. * @abstract
  41611. * @param {ProgrammableStage} program - The programmable stage.
  41612. */
  41613. createProgram( /*program*/ ) { }
  41614. /**
  41615. * Destroys the shader program of the given programmable stage.
  41616. *
  41617. * @abstract
  41618. * @param {ProgrammableStage} program - The programmable stage.
  41619. */
  41620. destroyProgram( /*program*/ ) { }
  41621. // bindings
  41622. /**
  41623. * Creates bindings from the given bind group definition.
  41624. *
  41625. * @abstract
  41626. * @param {BindGroup} bindGroup - The bind group.
  41627. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41628. * @param {number} cacheIndex - The cache index.
  41629. * @param {number} version - The version.
  41630. */
  41631. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  41632. /**
  41633. * Updates the given bind group definition.
  41634. *
  41635. * @abstract
  41636. * @param {BindGroup} bindGroup - The bind group.
  41637. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41638. * @param {number} cacheIndex - The cache index.
  41639. * @param {number} version - The version.
  41640. */
  41641. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  41642. /**
  41643. * Updates a buffer binding.
  41644. *
  41645. * @abstract
  41646. * @param {Buffer} binding - The buffer binding to update.
  41647. */
  41648. updateBinding( /*binding*/ ) { }
  41649. // pipeline
  41650. /**
  41651. * Creates a render pipeline for the given render object.
  41652. *
  41653. * @abstract
  41654. * @param {RenderObject} renderObject - The render object.
  41655. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  41656. */
  41657. createRenderPipeline( /*renderObject, promises*/ ) { }
  41658. /**
  41659. * Creates a compute pipeline for the given compute node.
  41660. *
  41661. * @abstract
  41662. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41663. * @param {Array<BindGroup>} bindings - The bindings.
  41664. */
  41665. createComputePipeline( /*computePipeline, bindings*/ ) { }
  41666. // cache key
  41667. /**
  41668. * Returns `true` if the render pipeline requires an update.
  41669. *
  41670. * @abstract
  41671. * @param {RenderObject} renderObject - The render object.
  41672. * @return {boolean} Whether the render pipeline requires an update or not.
  41673. */
  41674. needsRenderUpdate( /*renderObject*/ ) { }
  41675. /**
  41676. * Returns a cache key that is used to identify render pipelines.
  41677. *
  41678. * @abstract
  41679. * @param {RenderObject} renderObject - The render object.
  41680. * @return {string} The cache key.
  41681. */
  41682. getRenderCacheKey( /*renderObject*/ ) { }
  41683. // node builder
  41684. /**
  41685. * Returns a node builder for the given render object.
  41686. *
  41687. * @abstract
  41688. * @param {RenderObject} renderObject - The render object.
  41689. * @param {Renderer} renderer - The renderer.
  41690. * @return {NodeBuilder} The node builder.
  41691. */
  41692. createNodeBuilder( /*renderObject, renderer*/ ) { }
  41693. // textures
  41694. /**
  41695. * Creates a GPU sampler for the given texture.
  41696. *
  41697. * @abstract
  41698. * @param {Texture} texture - The texture to create the sampler for.
  41699. */
  41700. createSampler( /*texture*/ ) { }
  41701. /**
  41702. * Destroys the GPU sampler for the given texture.
  41703. *
  41704. * @abstract
  41705. * @param {Texture} texture - The texture to destroy the sampler for.
  41706. */
  41707. destroySampler( /*texture*/ ) {}
  41708. /**
  41709. * Creates a default texture for the given texture that can be used
  41710. * as a placeholder until the actual texture is ready for usage.
  41711. *
  41712. * @abstract
  41713. * @param {Texture} texture - The texture to create a default texture for.
  41714. */
  41715. createDefaultTexture( /*texture*/ ) { }
  41716. /**
  41717. * Defines a texture on the GPU for the given texture object.
  41718. *
  41719. * @abstract
  41720. * @param {Texture} texture - The texture.
  41721. * @param {Object} [options={}] - Optional configuration parameter.
  41722. */
  41723. createTexture( /*texture, options={}*/ ) { }
  41724. /**
  41725. * Uploads the updated texture data to the GPU.
  41726. *
  41727. * @abstract
  41728. * @param {Texture} texture - The texture.
  41729. * @param {Object} [options={}] - Optional configuration parameter.
  41730. */
  41731. updateTexture( /*texture, options = {}*/ ) { }
  41732. /**
  41733. * Generates mipmaps for the given texture.
  41734. *
  41735. * @abstract
  41736. * @param {Texture} texture - The texture.
  41737. */
  41738. generateMipmaps( /*texture*/ ) { }
  41739. /**
  41740. * Destroys the GPU data for the given texture object.
  41741. *
  41742. * @abstract
  41743. * @param {Texture} texture - The texture.
  41744. */
  41745. destroyTexture( /*texture*/ ) { }
  41746. /**
  41747. * Returns texture data as a typed array.
  41748. *
  41749. * @abstract
  41750. * @async
  41751. * @param {Texture} texture - The texture to copy.
  41752. * @param {number} x - The x coordinate of the copy origin.
  41753. * @param {number} y - The y coordinate of the copy origin.
  41754. * @param {number} width - The width of the copy.
  41755. * @param {number} height - The height of the copy.
  41756. * @param {number} faceIndex - The face index.
  41757. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  41758. */
  41759. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  41760. /**
  41761. * Copies data of the given source texture to the given destination texture.
  41762. *
  41763. * @abstract
  41764. * @param {Texture} srcTexture - The source texture.
  41765. * @param {Texture} dstTexture - The destination texture.
  41766. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  41767. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  41768. * @param {number} [srcLevel=0] - The source mip level to copy from.
  41769. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  41770. */
  41771. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  41772. /**
  41773. * Copies the current bound framebuffer to the given texture.
  41774. *
  41775. * @abstract
  41776. * @param {Texture} texture - The destination texture.
  41777. * @param {RenderContext} renderContext - The render context.
  41778. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  41779. */
  41780. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  41781. // attributes
  41782. /**
  41783. * Creates the GPU buffer of a shader attribute.
  41784. *
  41785. * @abstract
  41786. * @param {BufferAttribute} attribute - The buffer attribute.
  41787. */
  41788. createAttribute( /*attribute*/ ) { }
  41789. /**
  41790. * Creates the GPU buffer of an indexed shader attribute.
  41791. *
  41792. * @abstract
  41793. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  41794. */
  41795. createIndexAttribute( /*attribute*/ ) { }
  41796. /**
  41797. * Creates the GPU buffer of a storage attribute.
  41798. *
  41799. * @abstract
  41800. * @param {BufferAttribute} attribute - The buffer attribute.
  41801. */
  41802. createStorageAttribute( /*attribute*/ ) { }
  41803. /**
  41804. * Updates the GPU buffer of a shader attribute.
  41805. *
  41806. * @abstract
  41807. * @param {BufferAttribute} attribute - The buffer attribute to update.
  41808. */
  41809. updateAttribute( /*attribute*/ ) { }
  41810. /**
  41811. * Destroys the GPU buffer of a shader attribute.
  41812. *
  41813. * @abstract
  41814. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  41815. */
  41816. destroyAttribute( /*attribute*/ ) { }
  41817. // canvas
  41818. /**
  41819. * Returns the backend's rendering context.
  41820. *
  41821. * @abstract
  41822. * @return {Object} The rendering context.
  41823. */
  41824. getContext() { }
  41825. /**
  41826. * Backends can use this method if they have to run
  41827. * logic when the renderer gets resized.
  41828. *
  41829. * @abstract
  41830. */
  41831. updateSize() { }
  41832. /**
  41833. * Updates the viewport with the values from the given render context.
  41834. *
  41835. * @abstract
  41836. * @param {RenderContext} renderContext - The render context.
  41837. */
  41838. updateViewport( /*renderContext*/ ) {}
  41839. // utils
  41840. /**
  41841. * Returns `true` if the given 3D object is fully occluded by other
  41842. * 3D objects in the scene. Backends must implement this method by using
  41843. * a Occlusion Query API.
  41844. *
  41845. * @abstract
  41846. * @param {RenderContext} renderContext - The render context.
  41847. * @param {Object3D} object - The 3D object to test.
  41848. * @return {boolean} Whether the 3D object is fully occluded or not.
  41849. */
  41850. isOccluded( /*renderContext, object*/ ) {}
  41851. /**
  41852. * Resolves the time stamp for the given render context and type.
  41853. *
  41854. * @async
  41855. * @abstract
  41856. * @param {string} [type='render'] - The type of the time stamp.
  41857. * @return {Promise<number>} A Promise that resolves with the time stamp.
  41858. */
  41859. async resolveTimestampsAsync( type = 'render' ) {
  41860. if ( ! this.trackTimestamp ) {
  41861. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  41862. return;
  41863. }
  41864. const queryPool = this.timestampQueryPool[ type ];
  41865. if ( ! queryPool ) {
  41866. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  41867. return;
  41868. }
  41869. const duration = await queryPool.resolveQueriesAsync();
  41870. this.renderer.info[ type ].timestamp = duration;
  41871. return duration;
  41872. }
  41873. /**
  41874. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41875. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41876. *
  41877. * @async
  41878. * @abstract
  41879. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41880. */
  41881. async waitForGPU() {}
  41882. /**
  41883. * This method performs a readback operation by moving buffer data from
  41884. * a storage buffer attribute from the GPU to the CPU.
  41885. *
  41886. * @async
  41887. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41888. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41889. */
  41890. async getArrayBufferAsync( /* attribute */ ) {}
  41891. /**
  41892. * Checks if the given feature is supported by the backend.
  41893. *
  41894. * @async
  41895. * @abstract
  41896. * @param {string} name - The feature's name.
  41897. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  41898. */
  41899. async hasFeatureAsync( /*name*/ ) { }
  41900. /**
  41901. * Checks if the given feature is supported by the backend.
  41902. *
  41903. * @abstract
  41904. * @param {string} name - The feature's name.
  41905. * @return {boolean} Whether the feature is supported or not.
  41906. */
  41907. hasFeature( /*name*/ ) {}
  41908. /**
  41909. * Returns the maximum anisotropy texture filtering value.
  41910. *
  41911. * @abstract
  41912. * @return {number} The maximum anisotropy texture filtering value.
  41913. */
  41914. getMaxAnisotropy() {}
  41915. /**
  41916. * Returns the drawing buffer size.
  41917. *
  41918. * @return {Vector2} The drawing buffer size.
  41919. */
  41920. getDrawingBufferSize() {
  41921. _vector2 = _vector2 || new Vector2();
  41922. return this.renderer.getDrawingBufferSize( _vector2 );
  41923. }
  41924. /**
  41925. * Defines the scissor test.
  41926. *
  41927. * @abstract
  41928. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41929. */
  41930. setScissorTest( /*boolean*/ ) { }
  41931. /**
  41932. * Returns the clear color and alpha into a single
  41933. * color object.
  41934. *
  41935. * @return {Color4} The clear color.
  41936. */
  41937. getClearColor() {
  41938. const renderer = this.renderer;
  41939. _color4 = _color4 || new Color4();
  41940. renderer.getClearColor( _color4 );
  41941. _color4.getRGB( _color4 );
  41942. return _color4;
  41943. }
  41944. /**
  41945. * Returns the DOM element. If no DOM element exists, the backend
  41946. * creates a new one.
  41947. *
  41948. * @return {HTMLCanvasElement} The DOM element.
  41949. */
  41950. getDomElement() {
  41951. let domElement = this.domElement;
  41952. if ( domElement === null ) {
  41953. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  41954. // OffscreenCanvas does not have setAttribute, see #22811
  41955. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  41956. this.domElement = domElement;
  41957. }
  41958. return domElement;
  41959. }
  41960. /**
  41961. * Sets a dictionary for the given object into the
  41962. * internal data structure.
  41963. *
  41964. * @param {Object} object - The object.
  41965. * @param {Object} value - The dictionary to set.
  41966. */
  41967. set( object, value ) {
  41968. this.data.set( object, value );
  41969. }
  41970. /**
  41971. * Returns the dictionary for the given object.
  41972. *
  41973. * @param {Object} object - The object.
  41974. * @return {Object} The object's dictionary.
  41975. */
  41976. get( object ) {
  41977. let map = this.data.get( object );
  41978. if ( map === undefined ) {
  41979. map = {};
  41980. this.data.set( object, map );
  41981. }
  41982. return map;
  41983. }
  41984. /**
  41985. * Checks if the given object has a dictionary
  41986. * with data defined.
  41987. *
  41988. * @param {Object} object - The object.
  41989. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  41990. */
  41991. has( object ) {
  41992. return this.data.has( object );
  41993. }
  41994. /**
  41995. * Deletes an object from the internal data structure.
  41996. *
  41997. * @param {Object} object - The object to delete.
  41998. */
  41999. delete( object ) {
  42000. this.data.delete( object );
  42001. }
  42002. /**
  42003. * Frees internal resources.
  42004. *
  42005. * @abstract
  42006. */
  42007. dispose() { }
  42008. }
  42009. let _id$1 = 0;
  42010. /**
  42011. * This module is internally used in context of compute shaders.
  42012. * This type of shader is not natively supported in WebGL 2 and
  42013. * thus implemented via Transform Feedback. `DualAttributeData`
  42014. * manages the related data.
  42015. *
  42016. * @private
  42017. */
  42018. class DualAttributeData {
  42019. constructor( attributeData, dualBuffer ) {
  42020. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  42021. this.type = attributeData.type;
  42022. this.bufferType = attributeData.bufferType;
  42023. this.pbo = attributeData.pbo;
  42024. this.byteLength = attributeData.byteLength;
  42025. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  42026. this.version = attributeData.version;
  42027. this.isInteger = attributeData.isInteger;
  42028. this.activeBufferIndex = 0;
  42029. this.baseId = attributeData.id;
  42030. }
  42031. get id() {
  42032. return `${ this.baseId }|${ this.activeBufferIndex }`;
  42033. }
  42034. get bufferGPU() {
  42035. return this.buffers[ this.activeBufferIndex ];
  42036. }
  42037. get transformBuffer() {
  42038. return this.buffers[ this.activeBufferIndex ^ 1 ];
  42039. }
  42040. switchBuffers() {
  42041. this.activeBufferIndex ^= 1;
  42042. }
  42043. }
  42044. /**
  42045. * A WebGL 2 backend utility module for managing shader attributes.
  42046. *
  42047. * @private
  42048. */
  42049. class WebGLAttributeUtils {
  42050. /**
  42051. * Constructs a new utility object.
  42052. *
  42053. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42054. */
  42055. constructor( backend ) {
  42056. /**
  42057. * A reference to the WebGL 2 backend.
  42058. *
  42059. * @type {WebGLBackend}
  42060. */
  42061. this.backend = backend;
  42062. }
  42063. /**
  42064. * Creates the GPU buffer for the given buffer attribute.
  42065. *
  42066. * @param {BufferAttribute} attribute - The buffer attribute.
  42067. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  42068. */
  42069. createAttribute( attribute, bufferType ) {
  42070. const backend = this.backend;
  42071. const { gl } = backend;
  42072. const array = attribute.array;
  42073. const usage = attribute.usage || gl.STATIC_DRAW;
  42074. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42075. const bufferData = backend.get( bufferAttribute );
  42076. let bufferGPU = bufferData.bufferGPU;
  42077. if ( bufferGPU === undefined ) {
  42078. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  42079. bufferData.bufferGPU = bufferGPU;
  42080. bufferData.bufferType = bufferType;
  42081. bufferData.version = bufferAttribute.version;
  42082. }
  42083. //attribute.onUploadCallback();
  42084. let type;
  42085. if ( array instanceof Float32Array ) {
  42086. type = gl.FLOAT;
  42087. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42088. type = gl.HALF_FLOAT;
  42089. } else if ( array instanceof Uint16Array ) {
  42090. if ( attribute.isFloat16BufferAttribute ) {
  42091. type = gl.HALF_FLOAT;
  42092. } else {
  42093. type = gl.UNSIGNED_SHORT;
  42094. }
  42095. } else if ( array instanceof Int16Array ) {
  42096. type = gl.SHORT;
  42097. } else if ( array instanceof Uint32Array ) {
  42098. type = gl.UNSIGNED_INT;
  42099. } else if ( array instanceof Int32Array ) {
  42100. type = gl.INT;
  42101. } else if ( array instanceof Int8Array ) {
  42102. type = gl.BYTE;
  42103. } else if ( array instanceof Uint8Array ) {
  42104. type = gl.UNSIGNED_BYTE;
  42105. } else if ( array instanceof Uint8ClampedArray ) {
  42106. type = gl.UNSIGNED_BYTE;
  42107. } else {
  42108. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  42109. }
  42110. let attributeData = {
  42111. bufferGPU,
  42112. bufferType,
  42113. type,
  42114. byteLength: array.byteLength,
  42115. bytesPerElement: array.BYTES_PER_ELEMENT,
  42116. version: attribute.version,
  42117. pbo: attribute.pbo,
  42118. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  42119. id: _id$1 ++
  42120. };
  42121. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  42122. // create buffer for transform feedback use
  42123. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  42124. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  42125. }
  42126. backend.set( attribute, attributeData );
  42127. }
  42128. /**
  42129. * Updates the GPU buffer of the given buffer attribute.
  42130. *
  42131. * @param {BufferAttribute} attribute - The buffer attribute.
  42132. */
  42133. updateAttribute( attribute ) {
  42134. const backend = this.backend;
  42135. const { gl } = backend;
  42136. const array = attribute.array;
  42137. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42138. const bufferData = backend.get( bufferAttribute );
  42139. const bufferType = bufferData.bufferType;
  42140. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  42141. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  42142. if ( updateRanges.length === 0 ) {
  42143. // Not using update ranges
  42144. gl.bufferSubData( bufferType, 0, array );
  42145. } else {
  42146. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42147. const range = updateRanges[ i ];
  42148. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42149. array, range.start, range.count );
  42150. }
  42151. bufferAttribute.clearUpdateRanges();
  42152. }
  42153. gl.bindBuffer( bufferType, null );
  42154. bufferData.version = bufferAttribute.version;
  42155. }
  42156. /**
  42157. * Destroys the GPU buffer of the given buffer attribute.
  42158. *
  42159. * @param {BufferAttribute} attribute - The buffer attribute.
  42160. */
  42161. destroyAttribute( attribute ) {
  42162. const backend = this.backend;
  42163. const { gl } = backend;
  42164. if ( attribute.isInterleavedBufferAttribute ) {
  42165. backend.delete( attribute.data );
  42166. }
  42167. const attributeData = backend.get( attribute );
  42168. gl.deleteBuffer( attributeData.bufferGPU );
  42169. backend.delete( attribute );
  42170. }
  42171. /**
  42172. * This method performs a readback operation by moving buffer data from
  42173. * a storage buffer attribute from the GPU to the CPU.
  42174. *
  42175. * @async
  42176. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42177. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42178. */
  42179. async getArrayBufferAsync( attribute ) {
  42180. const backend = this.backend;
  42181. const { gl } = backend;
  42182. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42183. const { bufferGPU } = backend.get( bufferAttribute );
  42184. const array = attribute.array;
  42185. const byteLength = array.byteLength;
  42186. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  42187. const writeBuffer = gl.createBuffer();
  42188. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  42189. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  42190. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  42191. await backend.utils._clientWaitAsync();
  42192. const dstBuffer = new attribute.array.constructor( array.length );
  42193. // Ensure the buffer is bound before reading
  42194. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  42195. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  42196. gl.deleteBuffer( writeBuffer );
  42197. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  42198. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  42199. return dstBuffer.buffer;
  42200. }
  42201. /**
  42202. * Creates a WebGL buffer with the given data.
  42203. *
  42204. * @private
  42205. * @param {WebGL2RenderingContext} gl - The rendering context.
  42206. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  42207. * @param {TypedArray} array - The array of the buffer attribute.
  42208. * @param {GLenum} usage - The usage.
  42209. * @return {WebGLBuffer} The WebGL buffer.
  42210. */
  42211. _createBuffer( gl, bufferType, array, usage ) {
  42212. const bufferGPU = gl.createBuffer();
  42213. gl.bindBuffer( bufferType, bufferGPU );
  42214. gl.bufferData( bufferType, array, usage );
  42215. gl.bindBuffer( bufferType, null );
  42216. return bufferGPU;
  42217. }
  42218. }
  42219. let equationToGL, factorToGL;
  42220. /**
  42221. * A WebGL 2 backend utility module for managing the WebGL state.
  42222. *
  42223. * The major goal of this module is to reduce the number of state changes
  42224. * by caching the WEbGL state with a series of variables. In this way, the
  42225. * renderer only executes state change commands when necessary which
  42226. * improves the overall performance.
  42227. *
  42228. * @private
  42229. */
  42230. class WebGLState {
  42231. /**
  42232. * Constructs a new utility object.
  42233. *
  42234. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42235. */
  42236. constructor( backend ) {
  42237. /**
  42238. * A reference to the WebGL 2 backend.
  42239. *
  42240. * @type {WebGLBackend}
  42241. */
  42242. this.backend = backend;
  42243. /**
  42244. * A reference to the rendering context.
  42245. *
  42246. * @type {WebGL2RenderingContext}
  42247. */
  42248. this.gl = this.backend.gl;
  42249. // Below properties are intended to cache
  42250. // the WebGL state and are not explicitly
  42251. // documented for convenience reasons.
  42252. this.enabled = {};
  42253. this.currentFlipSided = null;
  42254. this.currentCullFace = null;
  42255. this.currentProgram = null;
  42256. this.currentBlendingEnabled = false;
  42257. this.currentBlending = null;
  42258. this.currentBlendSrc = null;
  42259. this.currentBlendDst = null;
  42260. this.currentBlendSrcAlpha = null;
  42261. this.currentBlendDstAlpha = null;
  42262. this.currentPremultipledAlpha = null;
  42263. this.currentPolygonOffsetFactor = null;
  42264. this.currentPolygonOffsetUnits = null;
  42265. this.currentColorMask = null;
  42266. this.currentDepthFunc = null;
  42267. this.currentDepthMask = null;
  42268. this.currentStencilFunc = null;
  42269. this.currentStencilRef = null;
  42270. this.currentStencilFuncMask = null;
  42271. this.currentStencilFail = null;
  42272. this.currentStencilZFail = null;
  42273. this.currentStencilZPass = null;
  42274. this.currentStencilMask = null;
  42275. this.currentLineWidth = null;
  42276. this.currentClippingPlanes = 0;
  42277. this.currentVAO = null;
  42278. this.currentIndex = null;
  42279. this.currentBoundFramebuffers = {};
  42280. this.currentDrawbuffers = new WeakMap();
  42281. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  42282. this.currentTextureSlot = null;
  42283. this.currentBoundTextures = {};
  42284. this.currentBoundBufferBases = {};
  42285. this._init();
  42286. }
  42287. /**
  42288. * Inits the state of the utility.
  42289. *
  42290. * @private
  42291. */
  42292. _init() {
  42293. const gl = this.gl;
  42294. // Store only WebGL constants here.
  42295. equationToGL = {
  42296. [ AddEquation ]: gl.FUNC_ADD,
  42297. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  42298. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  42299. };
  42300. factorToGL = {
  42301. [ ZeroFactor ]: gl.ZERO,
  42302. [ OneFactor ]: gl.ONE,
  42303. [ SrcColorFactor ]: gl.SRC_COLOR,
  42304. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  42305. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  42306. [ DstColorFactor ]: gl.DST_COLOR,
  42307. [ DstAlphaFactor ]: gl.DST_ALPHA,
  42308. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  42309. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  42310. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  42311. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  42312. };
  42313. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  42314. const viewportParam = gl.getParameter( gl.VIEWPORT );
  42315. this.currentScissor = new Vector4().fromArray( scissorParam );
  42316. this.currentViewport = new Vector4().fromArray( viewportParam );
  42317. this._tempVec4 = new Vector4();
  42318. }
  42319. /**
  42320. * Enables the given WebGL capability.
  42321. *
  42322. * This method caches the capability state so
  42323. * `gl.enable()` is only called when necessary.
  42324. *
  42325. * @param {GLenum} id - The capability to enable.
  42326. */
  42327. enable( id ) {
  42328. const { enabled } = this;
  42329. if ( enabled[ id ] !== true ) {
  42330. this.gl.enable( id );
  42331. enabled[ id ] = true;
  42332. }
  42333. }
  42334. /**
  42335. * Disables the given WebGL capability.
  42336. *
  42337. * This method caches the capability state so
  42338. * `gl.disable()` is only called when necessary.
  42339. *
  42340. * @param {GLenum} id - The capability to enable.
  42341. */
  42342. disable( id ) {
  42343. const { enabled } = this;
  42344. if ( enabled[ id ] !== false ) {
  42345. this.gl.disable( id );
  42346. enabled[ id ] = false;
  42347. }
  42348. }
  42349. /**
  42350. * Specifies whether polygons are front- or back-facing
  42351. * by setting the winding orientation.
  42352. *
  42353. * This method caches the state so `gl.frontFace()` is only
  42354. * called when necessary.
  42355. *
  42356. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  42357. */
  42358. setFlipSided( flipSided ) {
  42359. if ( this.currentFlipSided !== flipSided ) {
  42360. const { gl } = this;
  42361. if ( flipSided ) {
  42362. gl.frontFace( gl.CW );
  42363. } else {
  42364. gl.frontFace( gl.CCW );
  42365. }
  42366. this.currentFlipSided = flipSided;
  42367. }
  42368. }
  42369. /**
  42370. * Specifies whether or not front- and/or back-facing
  42371. * polygons can be culled.
  42372. *
  42373. * This method caches the state so `gl.cullFace()` is only
  42374. * called when necessary.
  42375. *
  42376. * @param {number} cullFace - Defines which polygons are candidates for culling.
  42377. */
  42378. setCullFace( cullFace ) {
  42379. const { gl } = this;
  42380. if ( cullFace !== CullFaceNone ) {
  42381. this.enable( gl.CULL_FACE );
  42382. if ( cullFace !== this.currentCullFace ) {
  42383. if ( cullFace === CullFaceBack ) {
  42384. gl.cullFace( gl.BACK );
  42385. } else if ( cullFace === CullFaceFront ) {
  42386. gl.cullFace( gl.FRONT );
  42387. } else {
  42388. gl.cullFace( gl.FRONT_AND_BACK );
  42389. }
  42390. }
  42391. } else {
  42392. this.disable( gl.CULL_FACE );
  42393. }
  42394. this.currentCullFace = cullFace;
  42395. }
  42396. /**
  42397. * Specifies the width of line primitives.
  42398. *
  42399. * This method caches the state so `gl.lineWidth()` is only
  42400. * called when necessary.
  42401. *
  42402. * @param {number} width - The line width.
  42403. */
  42404. setLineWidth( width ) {
  42405. const { currentLineWidth, gl } = this;
  42406. if ( width !== currentLineWidth ) {
  42407. gl.lineWidth( width );
  42408. this.currentLineWidth = width;
  42409. }
  42410. }
  42411. /**
  42412. * Defines the blending.
  42413. *
  42414. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  42415. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  42416. *
  42417. * @param {number} blending - The blending type.
  42418. * @param {number} blendEquation - The blending equation.
  42419. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  42420. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  42421. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  42422. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  42423. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  42424. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  42425. */
  42426. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  42427. const { gl } = this;
  42428. if ( blending === NoBlending ) {
  42429. if ( this.currentBlendingEnabled === true ) {
  42430. this.disable( gl.BLEND );
  42431. this.currentBlendingEnabled = false;
  42432. }
  42433. return;
  42434. }
  42435. if ( this.currentBlendingEnabled === false ) {
  42436. this.enable( gl.BLEND );
  42437. this.currentBlendingEnabled = true;
  42438. }
  42439. if ( blending !== CustomBlending ) {
  42440. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  42441. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  42442. gl.blendEquation( gl.FUNC_ADD );
  42443. this.currentBlendEquation = AddEquation;
  42444. this.currentBlendEquationAlpha = AddEquation;
  42445. }
  42446. if ( premultipliedAlpha ) {
  42447. switch ( blending ) {
  42448. case NormalBlending:
  42449. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  42450. break;
  42451. case AdditiveBlending:
  42452. gl.blendFunc( gl.ONE, gl.ONE );
  42453. break;
  42454. case SubtractiveBlending:
  42455. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  42456. break;
  42457. case MultiplyBlending:
  42458. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  42459. break;
  42460. default:
  42461. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  42462. break;
  42463. }
  42464. } else {
  42465. switch ( blending ) {
  42466. case NormalBlending:
  42467. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  42468. break;
  42469. case AdditiveBlending:
  42470. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  42471. break;
  42472. case SubtractiveBlending:
  42473. console.error( 'THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  42474. break;
  42475. case MultiplyBlending:
  42476. console.error( 'THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  42477. break;
  42478. default:
  42479. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  42480. break;
  42481. }
  42482. }
  42483. this.currentBlendSrc = null;
  42484. this.currentBlendDst = null;
  42485. this.currentBlendSrcAlpha = null;
  42486. this.currentBlendDstAlpha = null;
  42487. this.currentBlending = blending;
  42488. this.currentPremultipledAlpha = premultipliedAlpha;
  42489. }
  42490. return;
  42491. }
  42492. // custom blending
  42493. blendEquationAlpha = blendEquationAlpha || blendEquation;
  42494. blendSrcAlpha = blendSrcAlpha || blendSrc;
  42495. blendDstAlpha = blendDstAlpha || blendDst;
  42496. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  42497. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  42498. this.currentBlendEquation = blendEquation;
  42499. this.currentBlendEquationAlpha = blendEquationAlpha;
  42500. }
  42501. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  42502. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  42503. this.currentBlendSrc = blendSrc;
  42504. this.currentBlendDst = blendDst;
  42505. this.currentBlendSrcAlpha = blendSrcAlpha;
  42506. this.currentBlendDstAlpha = blendDstAlpha;
  42507. }
  42508. this.currentBlending = blending;
  42509. this.currentPremultipledAlpha = false;
  42510. }
  42511. /**
  42512. * Specifies whether colors can be written when rendering
  42513. * into a framebuffer or not.
  42514. *
  42515. * This method caches the state so `gl.colorMask()` is only
  42516. * called when necessary.
  42517. *
  42518. * @param {boolean} colorMask - The color mask.
  42519. */
  42520. setColorMask( colorMask ) {
  42521. if ( this.currentColorMask !== colorMask ) {
  42522. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  42523. this.currentColorMask = colorMask;
  42524. }
  42525. }
  42526. /**
  42527. * Specifies whether the depth test is enabled or not.
  42528. *
  42529. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  42530. */
  42531. setDepthTest( depthTest ) {
  42532. const { gl } = this;
  42533. if ( depthTest ) {
  42534. this.enable( gl.DEPTH_TEST );
  42535. } else {
  42536. this.disable( gl.DEPTH_TEST );
  42537. }
  42538. }
  42539. /**
  42540. * Specifies whether depth values can be written when rendering
  42541. * into a framebuffer or not.
  42542. *
  42543. * This method caches the state so `gl.depthMask()` is only
  42544. * called when necessary.
  42545. *
  42546. * @param {boolean} depthMask - The depth mask.
  42547. */
  42548. setDepthMask( depthMask ) {
  42549. if ( this.currentDepthMask !== depthMask ) {
  42550. this.gl.depthMask( depthMask );
  42551. this.currentDepthMask = depthMask;
  42552. }
  42553. }
  42554. /**
  42555. * Specifies the depth compare function.
  42556. *
  42557. * This method caches the state so `gl.depthFunc()` is only
  42558. * called when necessary.
  42559. *
  42560. * @param {number} depthFunc - The depth compare function.
  42561. */
  42562. setDepthFunc( depthFunc ) {
  42563. if ( this.currentDepthFunc !== depthFunc ) {
  42564. const { gl } = this;
  42565. switch ( depthFunc ) {
  42566. case NeverDepth:
  42567. gl.depthFunc( gl.NEVER );
  42568. break;
  42569. case AlwaysDepth:
  42570. gl.depthFunc( gl.ALWAYS );
  42571. break;
  42572. case LessDepth:
  42573. gl.depthFunc( gl.LESS );
  42574. break;
  42575. case LessEqualDepth:
  42576. gl.depthFunc( gl.LEQUAL );
  42577. break;
  42578. case EqualDepth:
  42579. gl.depthFunc( gl.EQUAL );
  42580. break;
  42581. case GreaterEqualDepth:
  42582. gl.depthFunc( gl.GEQUAL );
  42583. break;
  42584. case GreaterDepth:
  42585. gl.depthFunc( gl.GREATER );
  42586. break;
  42587. case NotEqualDepth:
  42588. gl.depthFunc( gl.NOTEQUAL );
  42589. break;
  42590. default:
  42591. gl.depthFunc( gl.LEQUAL );
  42592. }
  42593. this.currentDepthFunc = depthFunc;
  42594. }
  42595. }
  42596. /**
  42597. * Specifies the scissor box.
  42598. *
  42599. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  42600. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  42601. * @param {number} width - The width of the viewport.
  42602. * @param {number} height - The height of the viewport.
  42603. *
  42604. */
  42605. scissor( x, y, width, height ) {
  42606. const scissor = this._tempVec4.set( x, y, width, height );
  42607. if ( this.currentScissor.equals( scissor ) === false ) {
  42608. const { gl } = this;
  42609. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  42610. this.currentScissor.copy( scissor );
  42611. }
  42612. }
  42613. /**
  42614. * Specifies the viewport.
  42615. *
  42616. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  42617. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  42618. * @param {number} width - The width of the viewport.
  42619. * @param {number} height - The height of the viewport.
  42620. *
  42621. */
  42622. viewport( x, y, width, height ) {
  42623. const viewport = this._tempVec4.set( x, y, width, height );
  42624. if ( this.currentViewport.equals( viewport ) === false ) {
  42625. const { gl } = this;
  42626. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  42627. this.currentViewport.copy( viewport );
  42628. }
  42629. }
  42630. /**
  42631. * Defines the scissor test.
  42632. *
  42633. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42634. */
  42635. setScissorTest( boolean ) {
  42636. const gl = this.gl;
  42637. if ( boolean ) {
  42638. gl.enable( gl.SCISSOR_TEST );
  42639. } else {
  42640. gl.disable( gl.SCISSOR_TEST );
  42641. }
  42642. }
  42643. /**
  42644. * Specifies whether the stencil test is enabled or not.
  42645. *
  42646. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  42647. */
  42648. setStencilTest( stencilTest ) {
  42649. const { gl } = this;
  42650. if ( stencilTest ) {
  42651. this.enable( gl.STENCIL_TEST );
  42652. } else {
  42653. this.disable( gl.STENCIL_TEST );
  42654. }
  42655. }
  42656. /**
  42657. * Specifies whether stencil values can be written when rendering
  42658. * into a framebuffer or not.
  42659. *
  42660. * This method caches the state so `gl.stencilMask()` is only
  42661. * called when necessary.
  42662. *
  42663. * @param {boolean} stencilMask - The stencil mask.
  42664. */
  42665. setStencilMask( stencilMask ) {
  42666. if ( this.currentStencilMask !== stencilMask ) {
  42667. this.gl.stencilMask( stencilMask );
  42668. this.currentStencilMask = stencilMask;
  42669. }
  42670. }
  42671. /**
  42672. * Specifies whether the stencil test functions.
  42673. *
  42674. * This method caches the state so `gl.stencilFunc()` is only
  42675. * called when necessary.
  42676. *
  42677. * @param {number} stencilFunc - The stencil compare function.
  42678. * @param {number} stencilRef - The reference value for the stencil test.
  42679. * @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.
  42680. */
  42681. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  42682. if ( this.currentStencilFunc !== stencilFunc ||
  42683. this.currentStencilRef !== stencilRef ||
  42684. this.currentStencilFuncMask !== stencilMask ) {
  42685. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  42686. this.currentStencilFunc = stencilFunc;
  42687. this.currentStencilRef = stencilRef;
  42688. this.currentStencilFuncMask = stencilMask;
  42689. }
  42690. }
  42691. /**
  42692. * Specifies whether the stencil test operation.
  42693. *
  42694. * This method caches the state so `gl.stencilOp()` is only
  42695. * called when necessary.
  42696. *
  42697. * @param {number} stencilFail - The function to use when the stencil test fails.
  42698. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  42699. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  42700. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  42701. */
  42702. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  42703. if ( this.currentStencilFail !== stencilFail ||
  42704. this.currentStencilZFail !== stencilZFail ||
  42705. this.currentStencilZPass !== stencilZPass ) {
  42706. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  42707. this.currentStencilFail = stencilFail;
  42708. this.currentStencilZFail = stencilZFail;
  42709. this.currentStencilZPass = stencilZPass;
  42710. }
  42711. }
  42712. /**
  42713. * Configures the WebGL state for the given material.
  42714. *
  42715. * @param {Material} material - The material to configure the state for.
  42716. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  42717. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  42718. */
  42719. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  42720. const { gl } = this;
  42721. material.side === DoubleSide
  42722. ? this.disable( gl.CULL_FACE )
  42723. : this.enable( gl.CULL_FACE );
  42724. let flipSided = ( material.side === BackSide );
  42725. if ( frontFaceCW ) flipSided = ! flipSided;
  42726. this.setFlipSided( flipSided );
  42727. ( material.blending === NormalBlending && material.transparent === false )
  42728. ? this.setBlending( NoBlending )
  42729. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  42730. this.setDepthFunc( material.depthFunc );
  42731. this.setDepthTest( material.depthTest );
  42732. this.setDepthMask( material.depthWrite );
  42733. this.setColorMask( material.colorWrite );
  42734. const stencilWrite = material.stencilWrite;
  42735. this.setStencilTest( stencilWrite );
  42736. if ( stencilWrite ) {
  42737. this.setStencilMask( material.stencilWriteMask );
  42738. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  42739. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  42740. }
  42741. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  42742. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  42743. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  42744. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  42745. if ( hardwareClippingPlanes > 0 ) {
  42746. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  42747. const CLIP_DISTANCE0_WEBGL = 0x3000;
  42748. for ( let i = 0; i < 8; i ++ ) {
  42749. if ( i < hardwareClippingPlanes ) {
  42750. this.enable( CLIP_DISTANCE0_WEBGL + i );
  42751. } else {
  42752. this.disable( CLIP_DISTANCE0_WEBGL + i );
  42753. }
  42754. }
  42755. }
  42756. }
  42757. }
  42758. /**
  42759. * Specifies the polygon offset.
  42760. *
  42761. * This method caches the state so `gl.polygonOffset()` is only
  42762. * called when necessary.
  42763. *
  42764. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  42765. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  42766. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  42767. */
  42768. setPolygonOffset( polygonOffset, factor, units ) {
  42769. const { gl } = this;
  42770. if ( polygonOffset ) {
  42771. this.enable( gl.POLYGON_OFFSET_FILL );
  42772. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  42773. gl.polygonOffset( factor, units );
  42774. this.currentPolygonOffsetFactor = factor;
  42775. this.currentPolygonOffsetUnits = units;
  42776. }
  42777. } else {
  42778. this.disable( gl.POLYGON_OFFSET_FILL );
  42779. }
  42780. }
  42781. /**
  42782. * Defines the usage of the given WebGL program.
  42783. *
  42784. * This method caches the state so `gl.useProgram()` is only
  42785. * called when necessary.
  42786. *
  42787. * @param {WebGLProgram} program - The WebGL program to use.
  42788. * @return {boolean} Whether a program change has been executed or not.
  42789. */
  42790. useProgram( program ) {
  42791. if ( this.currentProgram !== program ) {
  42792. this.gl.useProgram( program );
  42793. this.currentProgram = program;
  42794. return true;
  42795. }
  42796. return false;
  42797. }
  42798. /**
  42799. * Sets the vertex state by binding the given VAO and element buffer.
  42800. *
  42801. * @param {WebGLVertexArrayObject} vao - The VAO.
  42802. * @param {WebGLBuffer} indexBuffer - The index buffer.
  42803. * @return {boolean} Whether a vertex state has been changed or not.
  42804. */
  42805. setVertexState( vao, indexBuffer = null ) {
  42806. const gl = this.gl;
  42807. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  42808. gl.bindVertexArray( vao );
  42809. if ( indexBuffer !== null ) {
  42810. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  42811. }
  42812. this.currentVAO = vao;
  42813. this.currentIndex = indexBuffer;
  42814. return true;
  42815. }
  42816. return false;
  42817. }
  42818. /**
  42819. * Resets the vertex array state by resetting the VAO and element buffer.
  42820. */
  42821. resetVertexState() {
  42822. const gl = this.gl;
  42823. gl.bindVertexArray( null );
  42824. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  42825. this.currentVAO = null;
  42826. this.currentIndex = null;
  42827. }
  42828. // framebuffer
  42829. /**
  42830. * Binds the given framebuffer.
  42831. *
  42832. * This method caches the state so `gl.bindFramebuffer()` is only
  42833. * called when necessary.
  42834. *
  42835. * @param {number} target - The binding point (target).
  42836. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  42837. * @return {boolean} Whether a bind has been executed or not.
  42838. */
  42839. bindFramebuffer( target, framebuffer ) {
  42840. const { gl, currentBoundFramebuffers } = this;
  42841. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  42842. gl.bindFramebuffer( target, framebuffer );
  42843. currentBoundFramebuffers[ target ] = framebuffer;
  42844. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  42845. if ( target === gl.DRAW_FRAMEBUFFER ) {
  42846. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  42847. }
  42848. if ( target === gl.FRAMEBUFFER ) {
  42849. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  42850. }
  42851. return true;
  42852. }
  42853. return false;
  42854. }
  42855. /**
  42856. * Defines draw buffers to which fragment colors are written into.
  42857. * Configures the MRT setup of custom framebuffers.
  42858. *
  42859. * This method caches the state so `gl.drawBuffers()` is only
  42860. * called when necessary.
  42861. *
  42862. * @param {RenderContext} renderContext - The render context.
  42863. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  42864. */
  42865. drawBuffers( renderContext, framebuffer ) {
  42866. const { gl } = this;
  42867. let drawBuffers = [];
  42868. let needsUpdate = false;
  42869. if ( renderContext.textures !== null ) {
  42870. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  42871. if ( drawBuffers === undefined ) {
  42872. drawBuffers = [];
  42873. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  42874. }
  42875. const textures = renderContext.textures;
  42876. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  42877. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  42878. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  42879. }
  42880. drawBuffers.length = textures.length;
  42881. needsUpdate = true;
  42882. }
  42883. } else {
  42884. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  42885. drawBuffers[ 0 ] = gl.BACK;
  42886. needsUpdate = true;
  42887. }
  42888. }
  42889. if ( needsUpdate ) {
  42890. gl.drawBuffers( drawBuffers );
  42891. }
  42892. }
  42893. // texture
  42894. /**
  42895. * Makes the given texture unit active.
  42896. *
  42897. * This method caches the state so `gl.activeTexture()` is only
  42898. * called when necessary.
  42899. *
  42900. * @param {number} webglSlot - The texture unit to make active.
  42901. */
  42902. activeTexture( webglSlot ) {
  42903. const { gl, currentTextureSlot, maxTextures } = this;
  42904. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  42905. if ( currentTextureSlot !== webglSlot ) {
  42906. gl.activeTexture( webglSlot );
  42907. this.currentTextureSlot = webglSlot;
  42908. }
  42909. }
  42910. /**
  42911. * Binds the given WebGL texture to a target.
  42912. *
  42913. * This method caches the state so `gl.bindTexture()` is only
  42914. * called when necessary.
  42915. *
  42916. * @param {number} webglType - The binding point (target).
  42917. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  42918. * @param {number} webglSlot - The texture.
  42919. */
  42920. bindTexture( webglType, webglTexture, webglSlot ) {
  42921. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  42922. if ( webglSlot === undefined ) {
  42923. if ( currentTextureSlot === null ) {
  42924. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  42925. } else {
  42926. webglSlot = currentTextureSlot;
  42927. }
  42928. }
  42929. let boundTexture = currentBoundTextures[ webglSlot ];
  42930. if ( boundTexture === undefined ) {
  42931. boundTexture = { type: undefined, texture: undefined };
  42932. currentBoundTextures[ webglSlot ] = boundTexture;
  42933. }
  42934. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  42935. if ( currentTextureSlot !== webglSlot ) {
  42936. gl.activeTexture( webglSlot );
  42937. this.currentTextureSlot = webglSlot;
  42938. }
  42939. gl.bindTexture( webglType, webglTexture );
  42940. boundTexture.type = webglType;
  42941. boundTexture.texture = webglTexture;
  42942. }
  42943. }
  42944. /**
  42945. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  42946. *
  42947. * This method caches the state so `gl.bindBufferBase()` is only
  42948. * called when necessary.
  42949. *
  42950. * @param {number} target - The target for the bind operation.
  42951. * @param {number} index - The index of the target.
  42952. * @param {WebGLBuffer} buffer - The WebGL buffer.
  42953. * @return {boolean} Whether a bind has been executed or not.
  42954. */
  42955. bindBufferBase( target, index, buffer ) {
  42956. const { gl } = this;
  42957. const key = `${target}-${index}`;
  42958. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  42959. gl.bindBufferBase( target, index, buffer );
  42960. this.currentBoundBufferBases[ key ] = buffer;
  42961. return true;
  42962. }
  42963. return false;
  42964. }
  42965. /**
  42966. * Unbinds the current bound texture.
  42967. *
  42968. * This method caches the state so `gl.bindTexture()` is only
  42969. * called when necessary.
  42970. */
  42971. unbindTexture() {
  42972. const { gl, currentTextureSlot, currentBoundTextures } = this;
  42973. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  42974. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  42975. gl.bindTexture( boundTexture.type, null );
  42976. boundTexture.type = undefined;
  42977. boundTexture.texture = undefined;
  42978. }
  42979. }
  42980. }
  42981. /**
  42982. * A WebGL 2 backend utility module with common helpers.
  42983. *
  42984. * @private
  42985. */
  42986. class WebGLUtils {
  42987. /**
  42988. * Constructs a new utility object.
  42989. *
  42990. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42991. */
  42992. constructor( backend ) {
  42993. /**
  42994. * A reference to the WebGL 2 backend.
  42995. *
  42996. * @type {WebGLBackend}
  42997. */
  42998. this.backend = backend;
  42999. /**
  43000. * A reference to the rendering context.
  43001. *
  43002. * @type {WebGL2RenderingContext}
  43003. */
  43004. this.gl = this.backend.gl;
  43005. /**
  43006. * A reference to a backend module holding extension-related
  43007. * utility functions.
  43008. *
  43009. * @type {WebGLExtensions}
  43010. */
  43011. this.extensions = backend.extensions;
  43012. }
  43013. /**
  43014. * Converts the given three.js constant into a WebGL constant.
  43015. * The method currently supports the conversion of texture formats
  43016. * and types.
  43017. *
  43018. * @param {number} p - The three.js constant.
  43019. * @param {string} [colorSpace=NoColorSpace] - The color space.
  43020. * @return {?number} The corresponding WebGL constant.
  43021. */
  43022. convert( p, colorSpace = NoColorSpace ) {
  43023. const { gl, extensions } = this;
  43024. let extension;
  43025. const transfer = ColorManagement.getTransfer( colorSpace );
  43026. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  43027. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  43028. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  43029. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  43030. if ( p === ByteType ) return gl.BYTE;
  43031. if ( p === ShortType ) return gl.SHORT;
  43032. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  43033. if ( p === IntType ) return gl.INT;
  43034. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  43035. if ( p === FloatType ) return gl.FLOAT;
  43036. if ( p === HalfFloatType ) {
  43037. return gl.HALF_FLOAT;
  43038. }
  43039. if ( p === AlphaFormat ) return gl.ALPHA;
  43040. if ( p === RGBFormat ) return gl.RGB;
  43041. if ( p === RGBAFormat ) return gl.RGBA;
  43042. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  43043. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  43044. // WebGL2 formats.
  43045. if ( p === RedFormat ) return gl.RED;
  43046. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  43047. if ( p === RGFormat ) return gl.RG;
  43048. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  43049. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  43050. // S3TC
  43051. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  43052. if ( transfer === SRGBTransfer ) {
  43053. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  43054. if ( extension !== null ) {
  43055. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  43056. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  43057. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  43058. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  43059. } else {
  43060. return null;
  43061. }
  43062. } else {
  43063. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  43064. if ( extension !== null ) {
  43065. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  43066. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  43067. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  43068. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  43069. } else {
  43070. return null;
  43071. }
  43072. }
  43073. }
  43074. // PVRTC
  43075. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  43076. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  43077. if ( extension !== null ) {
  43078. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  43079. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  43080. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  43081. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  43082. } else {
  43083. return null;
  43084. }
  43085. }
  43086. // ETC
  43087. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  43088. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  43089. if ( extension !== null ) {
  43090. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  43091. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  43092. } else {
  43093. return null;
  43094. }
  43095. }
  43096. // ASTC
  43097. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  43098. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  43099. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  43100. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  43101. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  43102. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  43103. if ( extension !== null ) {
  43104. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  43105. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  43106. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  43107. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  43108. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  43109. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  43110. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  43111. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  43112. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  43113. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  43114. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  43115. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  43116. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  43117. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  43118. } else {
  43119. return null;
  43120. }
  43121. }
  43122. // BPTC
  43123. if ( p === RGBA_BPTC_Format ) {
  43124. extension = extensions.get( 'EXT_texture_compression_bptc' );
  43125. if ( extension !== null ) {
  43126. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  43127. } else {
  43128. return null;
  43129. }
  43130. }
  43131. // RGTC
  43132. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  43133. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  43134. if ( extension !== null ) {
  43135. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  43136. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  43137. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  43138. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  43139. } else {
  43140. return null;
  43141. }
  43142. }
  43143. //
  43144. if ( p === UnsignedInt248Type ) {
  43145. return gl.UNSIGNED_INT_24_8;
  43146. }
  43147. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  43148. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  43149. }
  43150. /**
  43151. * This method can be used to synchronize the CPU with the GPU by waiting until
  43152. * ongoing GPU commands have been completed.
  43153. *
  43154. * @private
  43155. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  43156. */
  43157. _clientWaitAsync() {
  43158. const { gl } = this;
  43159. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  43160. gl.flush();
  43161. return new Promise( ( resolve, reject ) => {
  43162. function test() {
  43163. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  43164. if ( res === gl.WAIT_FAILED ) {
  43165. gl.deleteSync( sync );
  43166. reject();
  43167. return;
  43168. }
  43169. if ( res === gl.TIMEOUT_EXPIRED ) {
  43170. requestAnimationFrame( test );
  43171. return;
  43172. }
  43173. gl.deleteSync( sync );
  43174. resolve();
  43175. }
  43176. test();
  43177. } );
  43178. }
  43179. }
  43180. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  43181. /**
  43182. * A WebGL 2 backend utility module for managing textures.
  43183. *
  43184. * @private
  43185. */
  43186. class WebGLTextureUtils {
  43187. /**
  43188. * Constructs a new utility object.
  43189. *
  43190. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43191. */
  43192. constructor( backend ) {
  43193. /**
  43194. * A reference to the WebGL 2 backend.
  43195. *
  43196. * @type {WebGLBackend}
  43197. */
  43198. this.backend = backend;
  43199. /**
  43200. * A reference to the rendering context.
  43201. *
  43202. * @type {WebGL2RenderingContext}
  43203. */
  43204. this.gl = backend.gl;
  43205. /**
  43206. * A reference to a backend module holding extension-related
  43207. * utility functions.
  43208. *
  43209. * @type {WebGLExtensions}
  43210. */
  43211. this.extensions = backend.extensions;
  43212. /**
  43213. * A dictionary for managing default textures. The key
  43214. * is the binding point (target), the value the WEbGL texture object.
  43215. *
  43216. * @type {Object<GLenum,WebGLTexture>}
  43217. */
  43218. this.defaultTextures = {};
  43219. if ( initialized === false ) {
  43220. this._init();
  43221. initialized = true;
  43222. }
  43223. }
  43224. /**
  43225. * Inits the state of the utility.
  43226. *
  43227. * @private
  43228. */
  43229. _init() {
  43230. const gl = this.gl;
  43231. // Store only WebGL constants here.
  43232. wrappingToGL = {
  43233. [ RepeatWrapping ]: gl.REPEAT,
  43234. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  43235. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  43236. };
  43237. filterToGL = {
  43238. [ NearestFilter ]: gl.NEAREST,
  43239. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  43240. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  43241. [ LinearFilter ]: gl.LINEAR,
  43242. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  43243. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  43244. };
  43245. compareToGL = {
  43246. [ NeverCompare ]: gl.NEVER,
  43247. [ AlwaysCompare ]: gl.ALWAYS,
  43248. [ LessCompare ]: gl.LESS,
  43249. [ LessEqualCompare ]: gl.LEQUAL,
  43250. [ EqualCompare ]: gl.EQUAL,
  43251. [ GreaterEqualCompare ]: gl.GEQUAL,
  43252. [ GreaterCompare ]: gl.GREATER,
  43253. [ NotEqualCompare ]: gl.NOTEQUAL
  43254. };
  43255. }
  43256. /**
  43257. * Returns the native texture type for the given texture.
  43258. *
  43259. * @param {Texture} texture - The texture.
  43260. * @return {GLenum} The native texture type.
  43261. */
  43262. getGLTextureType( texture ) {
  43263. const { gl } = this;
  43264. let glTextureType;
  43265. if ( texture.isCubeTexture === true ) {
  43266. glTextureType = gl.TEXTURE_CUBE_MAP;
  43267. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43268. glTextureType = gl.TEXTURE_2D_ARRAY;
  43269. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  43270. glTextureType = gl.TEXTURE_3D;
  43271. } else {
  43272. glTextureType = gl.TEXTURE_2D;
  43273. }
  43274. return glTextureType;
  43275. }
  43276. /**
  43277. * Returns the native texture type for the given texture.
  43278. *
  43279. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  43280. * @param {GLenum} glFormat - The WebGL format.
  43281. * @param {GLenum} glType - The WebGL type.
  43282. * @param {string} colorSpace - The texture's color space.
  43283. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  43284. * @return {GLenum} The internal format.
  43285. */
  43286. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  43287. const { gl, extensions } = this;
  43288. if ( internalFormatName !== null ) {
  43289. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  43290. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  43291. }
  43292. let internalFormat = glFormat;
  43293. if ( glFormat === gl.RED ) {
  43294. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  43295. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  43296. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  43297. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  43298. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  43299. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  43300. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  43301. if ( glType === gl.INT ) internalFormat = gl.R32I;
  43302. }
  43303. if ( glFormat === gl.RED_INTEGER ) {
  43304. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  43305. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  43306. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  43307. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  43308. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  43309. if ( glType === gl.INT ) internalFormat = gl.R32I;
  43310. }
  43311. if ( glFormat === gl.RG ) {
  43312. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  43313. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  43314. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  43315. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  43316. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  43317. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  43318. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  43319. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  43320. }
  43321. if ( glFormat === gl.RG_INTEGER ) {
  43322. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  43323. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  43324. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  43325. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  43326. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  43327. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  43328. }
  43329. if ( glFormat === gl.RGB ) {
  43330. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  43331. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  43332. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  43333. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  43334. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  43335. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  43336. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  43337. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  43338. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  43339. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  43340. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  43341. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  43342. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  43343. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  43344. }
  43345. if ( glFormat === gl.RGB_INTEGER ) {
  43346. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  43347. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  43348. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  43349. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  43350. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  43351. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  43352. }
  43353. if ( glFormat === gl.RGBA ) {
  43354. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  43355. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  43356. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  43357. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  43358. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  43359. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  43360. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  43361. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  43362. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  43363. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  43364. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  43365. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  43366. }
  43367. if ( glFormat === gl.RGBA_INTEGER ) {
  43368. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  43369. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  43370. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  43371. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  43372. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  43373. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  43374. }
  43375. if ( glFormat === gl.DEPTH_COMPONENT ) {
  43376. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  43377. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  43378. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  43379. }
  43380. if ( glFormat === gl.DEPTH_STENCIL ) {
  43381. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  43382. }
  43383. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  43384. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  43385. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  43386. extensions.get( 'EXT_color_buffer_float' );
  43387. }
  43388. return internalFormat;
  43389. }
  43390. /**
  43391. * Sets the texture parameters for the given texture.
  43392. *
  43393. * @param {GLenum} textureType - The texture type.
  43394. * @param {Texture} texture - The texture.
  43395. */
  43396. setTextureParameters( textureType, texture ) {
  43397. const { gl, extensions, backend } = this;
  43398. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  43399. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  43400. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  43401. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  43402. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  43403. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  43404. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  43405. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  43406. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  43407. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  43408. // WebGL 2 does not support wrapping for depth 2D array textures
  43409. if ( ! texture.isArrayTexture ) {
  43410. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  43411. }
  43412. }
  43413. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  43414. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  43415. // follow WebGPU backend mapping for texture filtering
  43416. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  43417. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  43418. if ( texture.compareFunction ) {
  43419. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  43420. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  43421. }
  43422. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  43423. if ( texture.magFilter === NearestFilter ) return;
  43424. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  43425. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  43426. if ( texture.anisotropy > 1 ) {
  43427. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  43428. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  43429. }
  43430. }
  43431. }
  43432. /**
  43433. * Creates a default texture for the given texture that can be used
  43434. * as a placeholder until the actual texture is ready for usage.
  43435. *
  43436. * @param {Texture} texture - The texture to create a default texture for.
  43437. */
  43438. createDefaultTexture( texture ) {
  43439. const { gl, backend, defaultTextures } = this;
  43440. const glTextureType = this.getGLTextureType( texture );
  43441. let textureGPU = defaultTextures[ glTextureType ];
  43442. if ( textureGPU === undefined ) {
  43443. textureGPU = gl.createTexture();
  43444. backend.state.bindTexture( glTextureType, textureGPU );
  43445. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  43446. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  43447. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  43448. defaultTextures[ glTextureType ] = textureGPU;
  43449. }
  43450. backend.set( texture, {
  43451. textureGPU,
  43452. glTextureType,
  43453. isDefault: true
  43454. } );
  43455. }
  43456. /**
  43457. * Defines a texture on the GPU for the given texture object.
  43458. *
  43459. * @param {Texture} texture - The texture.
  43460. * @param {Object} [options={}] - Optional configuration parameter.
  43461. * @return {undefined}
  43462. */
  43463. createTexture( texture, options ) {
  43464. const { gl, backend } = this;
  43465. const { levels, width, height, depth } = options;
  43466. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  43467. const glType = backend.utils.convert( texture.type );
  43468. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  43469. const textureGPU = gl.createTexture();
  43470. const glTextureType = this.getGLTextureType( texture );
  43471. backend.state.bindTexture( glTextureType, textureGPU );
  43472. this.setTextureParameters( glTextureType, texture );
  43473. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  43474. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  43475. } else if ( texture.isData3DTexture ) {
  43476. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  43477. } else if ( ! texture.isVideoTexture ) {
  43478. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  43479. }
  43480. backend.set( texture, {
  43481. textureGPU,
  43482. glTextureType,
  43483. glFormat,
  43484. glType,
  43485. glInternalFormat
  43486. } );
  43487. }
  43488. /**
  43489. * Uploads texture buffer data to the GPU memory.
  43490. *
  43491. * @param {WebGLBuffer} buffer - The buffer data.
  43492. * @param {Texture} texture - The texture,
  43493. */
  43494. copyBufferToTexture( buffer, texture ) {
  43495. const { gl, backend } = this;
  43496. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  43497. const { width, height } = texture.source.data;
  43498. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  43499. backend.state.bindTexture( glTextureType, textureGPU );
  43500. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  43501. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  43502. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  43503. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  43504. backend.state.unbindTexture();
  43505. // debug
  43506. // const framebuffer = gl.createFramebuffer();
  43507. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  43508. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  43509. // const readout = new Float32Array( width * height * 4 );
  43510. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  43511. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  43512. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  43513. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  43514. // console.log( readout );
  43515. }
  43516. /**
  43517. * Uploads the updated texture data to the GPU.
  43518. *
  43519. * @param {Texture} texture - The texture.
  43520. * @param {Object} [options={}] - Optional configuration parameter.
  43521. */
  43522. updateTexture( texture, options ) {
  43523. const { gl } = this;
  43524. const { width, height } = options;
  43525. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  43526. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  43527. return;
  43528. this.backend.state.bindTexture( glTextureType, textureGPU );
  43529. this.setTextureParameters( glTextureType, texture );
  43530. if ( texture.isCompressedTexture ) {
  43531. const mipmaps = texture.mipmaps;
  43532. const image = options.image;
  43533. for ( let i = 0; i < mipmaps.length; i ++ ) {
  43534. const mipmap = mipmaps[ i ];
  43535. if ( texture.isCompressedArrayTexture ) {
  43536. if ( texture.format !== gl.RGBA ) {
  43537. if ( glFormat !== null ) {
  43538. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  43539. } else {
  43540. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  43541. }
  43542. } else {
  43543. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  43544. }
  43545. } else {
  43546. if ( glFormat !== null ) {
  43547. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  43548. } else {
  43549. console.warn( 'Unsupported compressed texture format' );
  43550. }
  43551. }
  43552. }
  43553. } else if ( texture.isCubeTexture ) {
  43554. const images = options.images;
  43555. for ( let i = 0; i < 6; i ++ ) {
  43556. const image = getImage( images[ i ] );
  43557. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  43558. }
  43559. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  43560. const image = options.image;
  43561. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  43562. } else if ( texture.isData3DTexture ) {
  43563. const image = options.image;
  43564. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  43565. } else if ( texture.isVideoTexture ) {
  43566. texture.update();
  43567. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  43568. } else {
  43569. const image = getImage( options.image );
  43570. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  43571. }
  43572. }
  43573. /**
  43574. * Generates mipmaps for the given texture.
  43575. *
  43576. * @param {Texture} texture - The texture.
  43577. */
  43578. generateMipmaps( texture ) {
  43579. const { gl, backend } = this;
  43580. const { textureGPU, glTextureType } = backend.get( texture );
  43581. backend.state.bindTexture( glTextureType, textureGPU );
  43582. gl.generateMipmap( glTextureType );
  43583. }
  43584. /**
  43585. * Deallocates the render buffers of the given render target.
  43586. *
  43587. * @param {RenderTarget} renderTarget - The render target.
  43588. */
  43589. deallocateRenderBuffers( renderTarget ) {
  43590. const { gl, backend } = this;
  43591. // remove framebuffer reference
  43592. if ( renderTarget ) {
  43593. const renderContextData = backend.get( renderTarget );
  43594. renderContextData.renderBufferStorageSetup = undefined;
  43595. if ( renderContextData.framebuffers ) {
  43596. for ( const cacheKey in renderContextData.framebuffers ) {
  43597. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  43598. }
  43599. delete renderContextData.framebuffers;
  43600. }
  43601. if ( renderContextData.depthRenderbuffer ) {
  43602. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  43603. delete renderContextData.depthRenderbuffer;
  43604. }
  43605. if ( renderContextData.stencilRenderbuffer ) {
  43606. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  43607. delete renderContextData.stencilRenderbuffer;
  43608. }
  43609. if ( renderContextData.msaaFrameBuffer ) {
  43610. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  43611. delete renderContextData.msaaFrameBuffer;
  43612. }
  43613. if ( renderContextData.msaaRenderbuffers ) {
  43614. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  43615. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  43616. }
  43617. delete renderContextData.msaaRenderbuffers;
  43618. }
  43619. }
  43620. }
  43621. /**
  43622. * Destroys the GPU data for the given texture object.
  43623. *
  43624. * @param {Texture} texture - The texture.
  43625. */
  43626. destroyTexture( texture ) {
  43627. const { gl, backend } = this;
  43628. const { textureGPU, renderTarget } = backend.get( texture );
  43629. this.deallocateRenderBuffers( renderTarget );
  43630. gl.deleteTexture( textureGPU );
  43631. backend.delete( texture );
  43632. }
  43633. /**
  43634. * Copies data of the given source texture to the given destination texture.
  43635. *
  43636. * @param {Texture} srcTexture - The source texture.
  43637. * @param {Texture} dstTexture - The destination texture.
  43638. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  43639. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  43640. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43641. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43642. */
  43643. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  43644. const { gl, backend } = this;
  43645. const { state } = this.backend;
  43646. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  43647. state.bindTexture( glTextureType, dstTextureGPU );
  43648. // gather the necessary dimensions to copy
  43649. let width, height, depth, minX, minY, minZ;
  43650. let dstX, dstY, dstZ;
  43651. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  43652. if ( srcRegion !== null ) {
  43653. width = srcRegion.max.x - srcRegion.min.x;
  43654. height = srcRegion.max.y - srcRegion.min.y;
  43655. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  43656. minX = srcRegion.min.x;
  43657. minY = srcRegion.min.y;
  43658. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  43659. } else {
  43660. const levelScale = Math.pow( 2, - srcLevel );
  43661. width = Math.floor( image.width * levelScale );
  43662. height = Math.floor( image.height * levelScale );
  43663. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  43664. depth = image.depth;
  43665. } else if ( srcTexture.isData3DTexture ) {
  43666. depth = Math.floor( image.depth * levelScale );
  43667. } else {
  43668. depth = 1;
  43669. }
  43670. minX = 0;
  43671. minY = 0;
  43672. minZ = 0;
  43673. }
  43674. if ( dstPosition !== null ) {
  43675. dstX = dstPosition.x;
  43676. dstY = dstPosition.y;
  43677. dstZ = dstPosition.z;
  43678. } else {
  43679. dstX = 0;
  43680. dstY = 0;
  43681. dstZ = 0;
  43682. }
  43683. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  43684. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  43685. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  43686. // used for copying data from cpu
  43687. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  43688. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  43689. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  43690. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  43691. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  43692. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  43693. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  43694. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  43695. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  43696. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  43697. // set up the src texture
  43698. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  43699. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  43700. const srcTextureData = backend.get( srcTexture );
  43701. const dstTextureData = backend.get( dstTexture );
  43702. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  43703. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  43704. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  43705. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  43706. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  43707. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  43708. let mask = gl.COLOR_BUFFER_BIT;
  43709. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  43710. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  43711. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  43712. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  43713. } else {
  43714. if ( isDst3D ) {
  43715. // copy data into the 3d texture
  43716. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  43717. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  43718. } else if ( dstTexture.isCompressedArrayTexture ) {
  43719. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  43720. } else {
  43721. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  43722. }
  43723. } else {
  43724. // copy data into the 2d texture
  43725. if ( srcTexture.isDataTexture ) {
  43726. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  43727. } else if ( srcTexture.isCompressedTexture ) {
  43728. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  43729. } else {
  43730. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  43731. }
  43732. }
  43733. }
  43734. // reset values
  43735. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  43736. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  43737. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  43738. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  43739. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  43740. // Generate mipmaps only when copying level 0
  43741. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  43742. gl.generateMipmap( glTextureType );
  43743. }
  43744. state.unbindTexture();
  43745. }
  43746. /**
  43747. * Copies the current bound framebuffer to the given texture.
  43748. *
  43749. * @param {Texture} texture - The destination texture.
  43750. * @param {RenderContext} renderContext - The render context.
  43751. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  43752. */
  43753. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  43754. const { gl } = this;
  43755. const { state } = this.backend;
  43756. const { textureGPU } = this.backend.get( texture );
  43757. const { x, y, z: width, w: height } = rectangle;
  43758. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  43759. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  43760. if ( requireDrawFrameBuffer ) {
  43761. const partial = ( x !== 0 || y !== 0 );
  43762. let mask;
  43763. let attachment;
  43764. if ( texture.isDepthTexture === true ) {
  43765. mask = gl.DEPTH_BUFFER_BIT;
  43766. attachment = gl.DEPTH_ATTACHMENT;
  43767. if ( renderContext.stencil ) {
  43768. mask |= gl.STENCIL_BUFFER_BIT;
  43769. }
  43770. } else {
  43771. mask = gl.COLOR_BUFFER_BIT;
  43772. attachment = gl.COLOR_ATTACHMENT0;
  43773. }
  43774. if ( partial ) {
  43775. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  43776. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  43777. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  43778. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43779. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  43780. const flippedY = srcHeight - y - height;
  43781. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  43782. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  43783. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  43784. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  43785. state.unbindTexture();
  43786. } else {
  43787. const fb = gl.createFramebuffer();
  43788. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43789. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  43790. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  43791. gl.deleteFramebuffer( fb );
  43792. }
  43793. } else {
  43794. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  43795. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  43796. state.unbindTexture();
  43797. }
  43798. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  43799. this.backend._setFramebuffer( renderContext );
  43800. }
  43801. /**
  43802. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  43803. *
  43804. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  43805. * @param {RenderContext} renderContext - The render context.
  43806. * @param {number} samples - The MSAA sample count.
  43807. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  43808. */
  43809. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  43810. const { gl } = this;
  43811. const renderTarget = renderContext.renderTarget;
  43812. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  43813. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  43814. if ( depthBuffer && ! stencilBuffer ) {
  43815. let glInternalFormat = gl.DEPTH_COMPONENT24;
  43816. if ( useMultisampledRTT === true ) {
  43817. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  43818. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  43819. } else if ( samples > 0 ) {
  43820. if ( depthTexture && depthTexture.isDepthTexture ) {
  43821. if ( depthTexture.type === gl.FLOAT ) {
  43822. glInternalFormat = gl.DEPTH_COMPONENT32F;
  43823. }
  43824. }
  43825. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  43826. } else {
  43827. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  43828. }
  43829. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  43830. } else if ( depthBuffer && stencilBuffer ) {
  43831. if ( samples > 0 ) {
  43832. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  43833. } else {
  43834. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  43835. }
  43836. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  43837. }
  43838. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  43839. }
  43840. /**
  43841. * Returns texture data as a typed array.
  43842. *
  43843. * @async
  43844. * @param {Texture} texture - The texture to copy.
  43845. * @param {number} x - The x coordinate of the copy origin.
  43846. * @param {number} y - The y coordinate of the copy origin.
  43847. * @param {number} width - The width of the copy.
  43848. * @param {number} height - The height of the copy.
  43849. * @param {number} faceIndex - The face index.
  43850. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43851. */
  43852. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43853. const { backend, gl } = this;
  43854. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  43855. const fb = gl.createFramebuffer();
  43856. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  43857. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  43858. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  43859. const typedArrayType = this._getTypedArrayType( glType );
  43860. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  43861. const elementCount = width * height;
  43862. const byteLength = elementCount * bytesPerTexel;
  43863. const buffer = gl.createBuffer();
  43864. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  43865. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  43866. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  43867. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  43868. await backend.utils._clientWaitAsync();
  43869. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  43870. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  43871. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  43872. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  43873. gl.deleteFramebuffer( fb );
  43874. return dstBuffer;
  43875. }
  43876. /**
  43877. * Returns the corresponding typed array type for the given WebGL data type.
  43878. *
  43879. * @private
  43880. * @param {GLenum} glType - The WebGL data type.
  43881. * @return {TypedArray.constructor} The typed array type.
  43882. */
  43883. _getTypedArrayType( glType ) {
  43884. const { gl } = this;
  43885. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  43886. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  43887. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  43888. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  43889. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  43890. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  43891. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  43892. if ( glType === gl.FLOAT ) return Float32Array;
  43893. throw new Error( `Unsupported WebGL type: ${glType}` );
  43894. }
  43895. /**
  43896. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  43897. *
  43898. * @private
  43899. * @param {GLenum} glType - The WebGL data type.
  43900. * @param {GLenum} glFormat - The WebGL texture format.
  43901. * @return {number} The bytes-per-texel.
  43902. */
  43903. _getBytesPerTexel( glType, glFormat ) {
  43904. const { gl } = this;
  43905. let bytesPerComponent = 0;
  43906. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  43907. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  43908. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  43909. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  43910. glType === gl.UNSIGNED_SHORT ||
  43911. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  43912. if ( glType === gl.UNSIGNED_INT ||
  43913. glType === gl.FLOAT ) bytesPerComponent = 4;
  43914. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  43915. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  43916. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  43917. }
  43918. }
  43919. function getImage( source ) {
  43920. if ( source.isDataTexture ) {
  43921. return source.image.data;
  43922. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  43923. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  43924. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  43925. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  43926. return source;
  43927. }
  43928. return source.data;
  43929. }
  43930. /**
  43931. * A WebGL 2 backend utility module for managing extensions.
  43932. *
  43933. * @private
  43934. */
  43935. class WebGLExtensions {
  43936. /**
  43937. * Constructs a new utility object.
  43938. *
  43939. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43940. */
  43941. constructor( backend ) {
  43942. /**
  43943. * A reference to the WebGL 2 backend.
  43944. *
  43945. * @type {WebGLBackend}
  43946. */
  43947. this.backend = backend;
  43948. /**
  43949. * A reference to the rendering context.
  43950. *
  43951. * @type {WebGL2RenderingContext}
  43952. */
  43953. this.gl = this.backend.gl;
  43954. /**
  43955. * A list with all the supported WebGL extensions.
  43956. *
  43957. * @type {Array<string>}
  43958. */
  43959. this.availableExtensions = this.gl.getSupportedExtensions();
  43960. /**
  43961. * A dictionary with requested WebGL extensions.
  43962. * The key is the name of the extension, the value
  43963. * the requested extension object.
  43964. *
  43965. * @type {Object<string,Object>}
  43966. */
  43967. this.extensions = {};
  43968. }
  43969. /**
  43970. * Returns the extension object for the given extension name.
  43971. *
  43972. * @param {string} name - The extension name.
  43973. * @return {Object} The extension object.
  43974. */
  43975. get( name ) {
  43976. let extension = this.extensions[ name ];
  43977. if ( extension === undefined ) {
  43978. extension = this.gl.getExtension( name );
  43979. this.extensions[ name ] = extension;
  43980. }
  43981. return extension;
  43982. }
  43983. /**
  43984. * Returns `true` if the requested extension is available.
  43985. *
  43986. * @param {string} name - The extension name.
  43987. * @return {boolean} Whether the given extension is available or not.
  43988. */
  43989. has( name ) {
  43990. return this.availableExtensions.includes( name );
  43991. }
  43992. }
  43993. /**
  43994. * A WebGL 2 backend utility module for managing the device's capabilities.
  43995. *
  43996. * @private
  43997. */
  43998. class WebGLCapabilities {
  43999. /**
  44000. * Constructs a new utility object.
  44001. *
  44002. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44003. */
  44004. constructor( backend ) {
  44005. /**
  44006. * A reference to the WebGL 2 backend.
  44007. *
  44008. * @type {WebGLBackend}
  44009. */
  44010. this.backend = backend;
  44011. /**
  44012. * This value holds the cached max anisotropy value.
  44013. *
  44014. * @type {?number}
  44015. * @default null
  44016. */
  44017. this.maxAnisotropy = null;
  44018. }
  44019. /**
  44020. * Returns the maximum anisotropy texture filtering value. This value
  44021. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  44022. * WebGL extension.
  44023. *
  44024. * @return {number} The maximum anisotropy texture filtering value.
  44025. */
  44026. getMaxAnisotropy() {
  44027. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  44028. const gl = this.backend.gl;
  44029. const extensions = this.backend.extensions;
  44030. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44031. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44032. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44033. } else {
  44034. this.maxAnisotropy = 0;
  44035. }
  44036. return this.maxAnisotropy;
  44037. }
  44038. }
  44039. const GLFeatureName = {
  44040. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  44041. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  44042. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  44043. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  44044. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  44045. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  44046. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  44047. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  44048. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  44049. 'OVR_multiview2': 'OVR_multiview2'
  44050. };
  44051. class WebGLBufferRenderer {
  44052. constructor( backend ) {
  44053. this.gl = backend.gl;
  44054. this.extensions = backend.extensions;
  44055. this.info = backend.renderer.info;
  44056. this.mode = null;
  44057. this.index = 0;
  44058. this.type = null;
  44059. this.object = null;
  44060. }
  44061. render( start, count ) {
  44062. const { gl, mode, object, type, info, index } = this;
  44063. if ( index !== 0 ) {
  44064. gl.drawElements( mode, count, type, start );
  44065. } else {
  44066. gl.drawArrays( mode, start, count );
  44067. }
  44068. info.update( object, count, 1 );
  44069. }
  44070. renderInstances( start, count, primcount ) {
  44071. const { gl, mode, type, index, object, info } = this;
  44072. if ( primcount === 0 ) return;
  44073. if ( index !== 0 ) {
  44074. gl.drawElementsInstanced( mode, count, type, start, primcount );
  44075. } else {
  44076. gl.drawArraysInstanced( mode, start, count, primcount );
  44077. }
  44078. info.update( object, count, primcount );
  44079. }
  44080. renderMultiDraw( starts, counts, drawCount ) {
  44081. const { extensions, mode, object, info } = this;
  44082. if ( drawCount === 0 ) return;
  44083. const extension = extensions.get( 'WEBGL_multi_draw' );
  44084. if ( extension === null ) {
  44085. for ( let i = 0; i < drawCount; i ++ ) {
  44086. this.render( starts[ i ], counts[ i ] );
  44087. }
  44088. } else {
  44089. if ( this.index !== 0 ) {
  44090. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  44091. } else {
  44092. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44093. }
  44094. let elementCount = 0;
  44095. for ( let i = 0; i < drawCount; i ++ ) {
  44096. elementCount += counts[ i ];
  44097. }
  44098. info.update( object, elementCount, 1 );
  44099. }
  44100. }
  44101. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44102. const { extensions, mode, object, info } = this;
  44103. if ( drawCount === 0 ) return;
  44104. const extension = extensions.get( 'WEBGL_multi_draw' );
  44105. if ( extension === null ) {
  44106. for ( let i = 0; i < drawCount; i ++ ) {
  44107. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44108. }
  44109. } else {
  44110. if ( this.index !== 0 ) {
  44111. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  44112. } else {
  44113. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44114. }
  44115. let elementCount = 0;
  44116. for ( let i = 0; i < drawCount; i ++ ) {
  44117. elementCount += counts[ i ] * primcount[ i ];
  44118. }
  44119. info.update( object, elementCount, 1 );
  44120. }
  44121. }
  44122. //
  44123. }
  44124. /**
  44125. * Abstract base class of a timestamp query pool.
  44126. *
  44127. * @abstract
  44128. */
  44129. class TimestampQueryPool {
  44130. /**
  44131. * Creates a new timestamp query pool.
  44132. *
  44133. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  44134. */
  44135. constructor( maxQueries = 256 ) {
  44136. /**
  44137. * Whether to track timestamps or not.
  44138. *
  44139. * @type {boolean}
  44140. * @default true
  44141. */
  44142. this.trackTimestamp = true;
  44143. /**
  44144. * Maximum number of queries this pool can hold.
  44145. *
  44146. * @type {number}
  44147. * @default 256
  44148. */
  44149. this.maxQueries = maxQueries;
  44150. /**
  44151. * How many queries allocated so far.
  44152. *
  44153. * @type {number}
  44154. * @default 0
  44155. */
  44156. this.currentQueryIndex = 0;
  44157. /**
  44158. * Tracks offsets for different contexts.
  44159. *
  44160. * @type {Map<string, number>}
  44161. */
  44162. this.queryOffsets = new Map();
  44163. /**
  44164. * Whether the pool has been disposed or not.
  44165. *
  44166. * @type {boolean}
  44167. * @default false
  44168. */
  44169. this.isDisposed = false;
  44170. /**
  44171. * TODO
  44172. *
  44173. * @type {number}
  44174. * @default 0
  44175. */
  44176. this.lastValue = 0;
  44177. /**
  44178. * TODO
  44179. *
  44180. * @type {boolean}
  44181. * @default false
  44182. */
  44183. this.pendingResolve = false;
  44184. }
  44185. /**
  44186. * Allocate queries for a specific renderContext.
  44187. *
  44188. * @abstract
  44189. * @param {Object} renderContext - The render context to allocate queries for.
  44190. * @returns {?number}
  44191. */
  44192. allocateQueriesForContext( /* renderContext */ ) {}
  44193. /**
  44194. * Resolve all timestamps and return data (or process them).
  44195. *
  44196. * @abstract
  44197. * @async
  44198. * @returns {Promise<number>|number} The resolved timestamp value.
  44199. */
  44200. async resolveQueriesAsync() {}
  44201. /**
  44202. * Dispose of the query pool.
  44203. *
  44204. * @abstract
  44205. */
  44206. dispose() {}
  44207. }
  44208. /**
  44209. * Manages a pool of WebGL timestamp queries for performance measurement.
  44210. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  44211. *
  44212. * @augments TimestampQueryPool
  44213. */
  44214. class WebGLTimestampQueryPool extends TimestampQueryPool {
  44215. /**
  44216. * Creates a new WebGL timestamp query pool.
  44217. *
  44218. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  44219. * @param {string} type - The type identifier for this query pool.
  44220. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  44221. */
  44222. constructor( gl, type, maxQueries = 2048 ) {
  44223. super( maxQueries );
  44224. this.gl = gl;
  44225. this.type = type;
  44226. // Check for timer query extensions
  44227. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  44228. gl.getExtension( 'EXT_disjoint_timer_query' );
  44229. if ( ! this.ext ) {
  44230. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  44231. this.trackTimestamp = false;
  44232. return;
  44233. }
  44234. // Create query objects
  44235. this.queries = [];
  44236. for ( let i = 0; i < this.maxQueries; i ++ ) {
  44237. this.queries.push( gl.createQuery() );
  44238. }
  44239. this.activeQuery = null;
  44240. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  44241. }
  44242. /**
  44243. * Allocates a pair of queries for a given render context.
  44244. *
  44245. * @param {Object} renderContext - The render context to allocate queries for.
  44246. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  44247. */
  44248. allocateQueriesForContext( renderContext ) {
  44249. if ( ! this.trackTimestamp ) return null;
  44250. // Check if we have enough space for a new query pair
  44251. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  44252. 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() } ).` );
  44253. return null;
  44254. }
  44255. const baseOffset = this.currentQueryIndex;
  44256. this.currentQueryIndex += 2;
  44257. // Initialize query states
  44258. this.queryStates.set( baseOffset, 'inactive' );
  44259. this.queryOffsets.set( renderContext.id, baseOffset );
  44260. return baseOffset;
  44261. }
  44262. /**
  44263. * Begins a timestamp query for the specified render context.
  44264. *
  44265. * @param {Object} renderContext - The render context to begin timing for.
  44266. */
  44267. beginQuery( renderContext ) {
  44268. if ( ! this.trackTimestamp || this.isDisposed ) {
  44269. return;
  44270. }
  44271. const baseOffset = this.queryOffsets.get( renderContext.id );
  44272. if ( baseOffset == null ) {
  44273. return;
  44274. }
  44275. // Don't start a new query if there's an active one
  44276. if ( this.activeQuery !== null ) {
  44277. return;
  44278. }
  44279. const query = this.queries[ baseOffset ];
  44280. if ( ! query ) {
  44281. return;
  44282. }
  44283. try {
  44284. // Only begin if query is inactive
  44285. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  44286. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  44287. this.activeQuery = baseOffset;
  44288. this.queryStates.set( baseOffset, 'started' );
  44289. }
  44290. } catch ( error ) {
  44291. console.error( 'Error in beginQuery:', error );
  44292. this.activeQuery = null;
  44293. this.queryStates.set( baseOffset, 'inactive' );
  44294. }
  44295. }
  44296. /**
  44297. * Ends the active timestamp query for the specified render context.
  44298. *
  44299. * @param {Object} renderContext - The render context to end timing for.
  44300. * @param {string} renderContext.id - Unique identifier for the render context.
  44301. */
  44302. endQuery( renderContext ) {
  44303. if ( ! this.trackTimestamp || this.isDisposed ) {
  44304. return;
  44305. }
  44306. const baseOffset = this.queryOffsets.get( renderContext.id );
  44307. if ( baseOffset == null ) {
  44308. return;
  44309. }
  44310. // Only end if this is the active query
  44311. if ( this.activeQuery !== baseOffset ) {
  44312. return;
  44313. }
  44314. try {
  44315. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  44316. this.queryStates.set( baseOffset, 'ended' );
  44317. this.activeQuery = null;
  44318. } catch ( error ) {
  44319. console.error( 'Error in endQuery:', error );
  44320. // Reset state on error
  44321. this.queryStates.set( baseOffset, 'inactive' );
  44322. this.activeQuery = null;
  44323. }
  44324. }
  44325. /**
  44326. * Asynchronously resolves all completed queries and returns the total duration.
  44327. *
  44328. * @async
  44329. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  44330. */
  44331. async resolveQueriesAsync() {
  44332. if ( ! this.trackTimestamp || this.pendingResolve ) {
  44333. return this.lastValue;
  44334. }
  44335. this.pendingResolve = true;
  44336. try {
  44337. // Wait for all ended queries to complete
  44338. const resolvePromises = [];
  44339. for ( const [ baseOffset, state ] of this.queryStates ) {
  44340. if ( state === 'ended' ) {
  44341. const query = this.queries[ baseOffset ];
  44342. resolvePromises.push( this.resolveQuery( query ) );
  44343. }
  44344. }
  44345. if ( resolvePromises.length === 0 ) {
  44346. return this.lastValue;
  44347. }
  44348. const results = await Promise.all( resolvePromises );
  44349. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  44350. // Store the last valid result
  44351. this.lastValue = totalDuration;
  44352. // Reset states
  44353. this.currentQueryIndex = 0;
  44354. this.queryOffsets.clear();
  44355. this.queryStates.clear();
  44356. this.activeQuery = null;
  44357. return totalDuration;
  44358. } catch ( error ) {
  44359. console.error( 'Error resolving queries:', error );
  44360. return this.lastValue;
  44361. } finally {
  44362. this.pendingResolve = false;
  44363. }
  44364. }
  44365. /**
  44366. * Resolves a single query, checking for completion and disjoint operation.
  44367. *
  44368. * @async
  44369. * @param {WebGLQuery} query - The query object to resolve.
  44370. * @returns {Promise<number>} The elapsed time in milliseconds.
  44371. */
  44372. async resolveQuery( query ) {
  44373. return new Promise( ( resolve ) => {
  44374. if ( this.isDisposed ) {
  44375. resolve( this.lastValue );
  44376. return;
  44377. }
  44378. let timeoutId;
  44379. let isResolved = false;
  44380. const cleanup = () => {
  44381. if ( timeoutId ) {
  44382. clearTimeout( timeoutId );
  44383. timeoutId = null;
  44384. }
  44385. };
  44386. const finalizeResolution = ( value ) => {
  44387. if ( ! isResolved ) {
  44388. isResolved = true;
  44389. cleanup();
  44390. resolve( value );
  44391. }
  44392. };
  44393. const checkQuery = () => {
  44394. if ( this.isDisposed ) {
  44395. finalizeResolution( this.lastValue );
  44396. return;
  44397. }
  44398. try {
  44399. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  44400. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  44401. if ( disjoint ) {
  44402. finalizeResolution( this.lastValue );
  44403. return;
  44404. }
  44405. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  44406. if ( ! available ) {
  44407. timeoutId = setTimeout( checkQuery, 1 );
  44408. return;
  44409. }
  44410. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  44411. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  44412. } catch ( error ) {
  44413. console.error( 'Error checking query:', error );
  44414. resolve( this.lastValue );
  44415. }
  44416. };
  44417. checkQuery();
  44418. } );
  44419. }
  44420. /**
  44421. * Releases all resources held by this query pool.
  44422. * This includes deleting all query objects and clearing internal state.
  44423. */
  44424. dispose() {
  44425. if ( this.isDisposed ) {
  44426. return;
  44427. }
  44428. this.isDisposed = true;
  44429. if ( ! this.trackTimestamp ) return;
  44430. for ( const query of this.queries ) {
  44431. this.gl.deleteQuery( query );
  44432. }
  44433. this.queries = [];
  44434. this.queryStates.clear();
  44435. this.queryOffsets.clear();
  44436. this.lastValue = 0;
  44437. this.activeQuery = null;
  44438. }
  44439. }
  44440. /**
  44441. * A backend implementation targeting WebGL 2.
  44442. *
  44443. * @private
  44444. * @augments Backend
  44445. */
  44446. class WebGLBackend extends Backend {
  44447. /**
  44448. * WebGLBackend options.
  44449. *
  44450. * @typedef {Object} WebGLBackend~Options
  44451. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  44452. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  44453. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  44454. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  44455. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  44456. * @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.
  44457. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  44458. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  44459. */
  44460. /**
  44461. * Constructs a new WebGPU backend.
  44462. *
  44463. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  44464. */
  44465. constructor( parameters = {} ) {
  44466. super( parameters );
  44467. /**
  44468. * This flag can be used for type testing.
  44469. *
  44470. * @type {boolean}
  44471. * @readonly
  44472. * @default true
  44473. */
  44474. this.isWebGLBackend = true;
  44475. /**
  44476. * A reference to a backend module holding shader attribute-related
  44477. * utility functions.
  44478. *
  44479. * @type {?WebGLAttributeUtils}
  44480. * @default null
  44481. */
  44482. this.attributeUtils = null;
  44483. /**
  44484. * A reference to a backend module holding extension-related
  44485. * utility functions.
  44486. *
  44487. * @type {?WebGLExtensions}
  44488. * @default null
  44489. */
  44490. this.extensions = null;
  44491. /**
  44492. * A reference to a backend module holding capability-related
  44493. * utility functions.
  44494. *
  44495. * @type {?WebGLCapabilities}
  44496. * @default null
  44497. */
  44498. this.capabilities = null;
  44499. /**
  44500. * A reference to a backend module holding texture-related
  44501. * utility functions.
  44502. *
  44503. * @type {?WebGLTextureUtils}
  44504. * @default null
  44505. */
  44506. this.textureUtils = null;
  44507. /**
  44508. * A reference to a backend module holding renderer-related
  44509. * utility functions.
  44510. *
  44511. * @type {?WebGLBufferRenderer}
  44512. * @default null
  44513. */
  44514. this.bufferRenderer = null;
  44515. /**
  44516. * A reference to the rendering context.
  44517. *
  44518. * @type {?WebGL2RenderingContext}
  44519. * @default null
  44520. */
  44521. this.gl = null;
  44522. /**
  44523. * A reference to a backend module holding state-related
  44524. * utility functions.
  44525. *
  44526. * @type {?WebGLState}
  44527. * @default null
  44528. */
  44529. this.state = null;
  44530. /**
  44531. * A reference to a backend module holding common
  44532. * utility functions.
  44533. *
  44534. * @type {?WebGLUtils}
  44535. * @default null
  44536. */
  44537. this.utils = null;
  44538. /**
  44539. * Dictionary for caching VAOs.
  44540. *
  44541. * @type {Object<string,WebGLVertexArrayObject>}
  44542. */
  44543. this.vaoCache = {};
  44544. /**
  44545. * Dictionary for caching transform feedback objects.
  44546. *
  44547. * @type {Object<string,WebGLTransformFeedback>}
  44548. */
  44549. this.transformFeedbackCache = {};
  44550. /**
  44551. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  44552. * Only relevant when using compute shaders.
  44553. *
  44554. * @type {boolean}
  44555. * @default false
  44556. */
  44557. this.discard = false;
  44558. /**
  44559. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  44560. * device does not support the extension.
  44561. *
  44562. * @type {?EXTDisjointTimerQueryWebGL2}
  44563. * @default null
  44564. */
  44565. this.disjoint = null;
  44566. /**
  44567. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  44568. * device does not support the extension.
  44569. *
  44570. * @type {?KHRParallelShaderCompile}
  44571. * @default null
  44572. */
  44573. this.parallel = null;
  44574. /**
  44575. * A reference to the current render context.
  44576. *
  44577. * @private
  44578. * @type {RenderContext}
  44579. * @default null
  44580. */
  44581. this._currentContext = null;
  44582. /**
  44583. * A unique collection of bindings.
  44584. *
  44585. * @private
  44586. * @type {WeakSet<Array<BindGroup>>}
  44587. */
  44588. this._knownBindings = new WeakSet();
  44589. /**
  44590. * Whether the device supports framebuffers invalidation or not.
  44591. *
  44592. * @private
  44593. * @type {boolean}
  44594. */
  44595. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  44596. /**
  44597. * The target framebuffer when rendering with
  44598. * the WebXR device API.
  44599. *
  44600. * @private
  44601. * @type {WebGLFramebuffer}
  44602. * @default null
  44603. */
  44604. this._xrFramebuffer = null;
  44605. }
  44606. /**
  44607. * Initializes the backend so it is ready for usage.
  44608. *
  44609. * @param {Renderer} renderer - The renderer.
  44610. */
  44611. init( renderer ) {
  44612. super.init( renderer );
  44613. //
  44614. const parameters = this.parameters;
  44615. const contextAttributes = {
  44616. antialias: renderer.samples > 0,
  44617. alpha: true, // always true for performance reasons
  44618. depth: renderer.depth,
  44619. stencil: renderer.stencil
  44620. };
  44621. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  44622. function onContextLost( event ) {
  44623. event.preventDefault();
  44624. const contextLossInfo = {
  44625. api: 'WebGL',
  44626. message: event.statusMessage || 'Unknown reason',
  44627. reason: null,
  44628. originalEvent: event
  44629. };
  44630. renderer.onDeviceLost( contextLossInfo );
  44631. }
  44632. this._onContextLost = onContextLost;
  44633. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  44634. this.gl = glContext;
  44635. this.extensions = new WebGLExtensions( this );
  44636. this.capabilities = new WebGLCapabilities( this );
  44637. this.attributeUtils = new WebGLAttributeUtils( this );
  44638. this.textureUtils = new WebGLTextureUtils( this );
  44639. this.bufferRenderer = new WebGLBufferRenderer( this );
  44640. this.state = new WebGLState( this );
  44641. this.utils = new WebGLUtils( this );
  44642. this.extensions.get( 'EXT_color_buffer_float' );
  44643. this.extensions.get( 'WEBGL_clip_cull_distance' );
  44644. this.extensions.get( 'OES_texture_float_linear' );
  44645. this.extensions.get( 'EXT_color_buffer_half_float' );
  44646. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  44647. this.extensions.get( 'WEBGL_render_shared_exponent' );
  44648. this.extensions.get( 'WEBGL_multi_draw' );
  44649. this.extensions.get( 'OVR_multiview2' );
  44650. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  44651. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  44652. }
  44653. /**
  44654. * The coordinate system of the backend.
  44655. *
  44656. * @type {number}
  44657. * @readonly
  44658. */
  44659. get coordinateSystem() {
  44660. return WebGLCoordinateSystem;
  44661. }
  44662. /**
  44663. * This method performs a readback operation by moving buffer data from
  44664. * a storage buffer attribute from the GPU to the CPU.
  44665. *
  44666. * @async
  44667. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44668. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44669. */
  44670. async getArrayBufferAsync( attribute ) {
  44671. return await this.attributeUtils.getArrayBufferAsync( attribute );
  44672. }
  44673. /**
  44674. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  44675. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  44676. *
  44677. * @async
  44678. * @return {Promise} A Promise that resolves when synchronization has been finished.
  44679. */
  44680. async waitForGPU() {
  44681. await this.utils._clientWaitAsync();
  44682. }
  44683. /**
  44684. * Ensures the backend is XR compatible.
  44685. *
  44686. * @async
  44687. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  44688. */
  44689. async makeXRCompatible() {
  44690. const attributes = this.gl.getContextAttributes();
  44691. if ( attributes.xrCompatible !== true ) {
  44692. await this.gl.makeXRCompatible();
  44693. }
  44694. }
  44695. /**
  44696. * Sets the XR rendering destination.
  44697. *
  44698. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  44699. */
  44700. setXRTarget( xrFramebuffer ) {
  44701. this._xrFramebuffer = xrFramebuffer;
  44702. }
  44703. /**
  44704. * Configures the given XR render target with external textures.
  44705. *
  44706. * This method is only relevant when using the WebXR Layers API.
  44707. *
  44708. * @param {XRRenderTarget} renderTarget - The XR render target.
  44709. * @param {WebGLTexture} colorTexture - A native color texture.
  44710. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  44711. */
  44712. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  44713. const gl = this.gl;
  44714. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  44715. if ( depthTexture !== null ) {
  44716. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  44717. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  44718. // The multisample_render_to_texture extension doesn't work properly if there
  44719. // are midframe flushes and an external depth texture.
  44720. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  44721. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  44722. }
  44723. renderTarget._autoAllocateDepthBuffer = false;
  44724. }
  44725. }
  44726. /**
  44727. * Inits a time stamp query for the given render context.
  44728. *
  44729. * @param {RenderContext} renderContext - The render context.
  44730. */
  44731. initTimestampQuery( renderContext ) {
  44732. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  44733. const type = renderContext.isComputeNode ? 'compute' : 'render';
  44734. if ( ! this.timestampQueryPool[ type ] ) {
  44735. // TODO: Variable maxQueries?
  44736. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  44737. }
  44738. const timestampQueryPool = this.timestampQueryPool[ type ];
  44739. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  44740. if ( baseOffset !== null ) {
  44741. timestampQueryPool.beginQuery( renderContext );
  44742. }
  44743. }
  44744. // timestamp utils
  44745. /**
  44746. * Prepares the timestamp buffer.
  44747. *
  44748. * @param {RenderContext} renderContext - The render context.
  44749. */
  44750. prepareTimestampBuffer( renderContext ) {
  44751. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  44752. const type = renderContext.isComputeNode ? 'compute' : 'render';
  44753. const timestampQueryPool = this.timestampQueryPool[ type ];
  44754. timestampQueryPool.endQuery( renderContext );
  44755. }
  44756. /**
  44757. * Returns the backend's rendering context.
  44758. *
  44759. * @return {WebGL2RenderingContext} The rendering context.
  44760. */
  44761. getContext() {
  44762. return this.gl;
  44763. }
  44764. /**
  44765. * This method is executed at the beginning of a render call and prepares
  44766. * the WebGL state for upcoming render calls
  44767. *
  44768. * @param {RenderContext} renderContext - The render context.
  44769. */
  44770. beginRender( renderContext ) {
  44771. const { state } = this;
  44772. const renderContextData = this.get( renderContext );
  44773. //
  44774. if ( renderContext.viewport ) {
  44775. this.updateViewport( renderContext );
  44776. } else {
  44777. const { width, height } = this.getDrawingBufferSize();
  44778. state.viewport( 0, 0, width, height );
  44779. }
  44780. if ( renderContext.scissor ) {
  44781. const { x, y, width, height } = renderContext.scissorValue;
  44782. state.scissor( x, renderContext.height - height - y, width, height );
  44783. }
  44784. //
  44785. this.initTimestampQuery( renderContext );
  44786. renderContextData.previousContext = this._currentContext;
  44787. this._currentContext = renderContext;
  44788. this._setFramebuffer( renderContext );
  44789. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  44790. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44791. if ( occlusionQueryCount > 0 ) {
  44792. // Get a reference to the array of objects with queries. The renderContextData property
  44793. // can be changed by another render pass before the async reading of all previous queries complete
  44794. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  44795. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  44796. renderContextData.lastOcclusionObject = null;
  44797. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  44798. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  44799. renderContextData.occlusionQueryIndex = 0;
  44800. }
  44801. }
  44802. /**
  44803. * This method is executed at the end of a render call and finalizes work
  44804. * after draw calls.
  44805. *
  44806. * @param {RenderContext} renderContext - The render context.
  44807. */
  44808. finishRender( renderContext ) {
  44809. const { gl, state } = this;
  44810. const renderContextData = this.get( renderContext );
  44811. const previousContext = renderContextData.previousContext;
  44812. state.resetVertexState();
  44813. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44814. if ( occlusionQueryCount > 0 ) {
  44815. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  44816. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  44817. }
  44818. this.resolveOccludedAsync( renderContext );
  44819. }
  44820. const textures = renderContext.textures;
  44821. if ( textures !== null ) {
  44822. for ( let i = 0; i < textures.length; i ++ ) {
  44823. const texture = textures[ i ];
  44824. if ( texture.generateMipmaps ) {
  44825. this.generateMipmaps( texture );
  44826. }
  44827. }
  44828. }
  44829. this._currentContext = previousContext;
  44830. const renderTarget = renderContext.renderTarget;
  44831. if ( renderContext.textures !== null && renderTarget ) {
  44832. const renderTargetContextData = this.get( renderTarget );
  44833. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  44834. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  44835. let mask = gl.COLOR_BUFFER_BIT;
  44836. if ( renderTarget.resolveDepthBuffer ) {
  44837. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  44838. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  44839. }
  44840. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  44841. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  44842. const textures = renderContext.textures;
  44843. const isMRT = textures.length > 1;
  44844. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  44845. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44846. if ( isMRT ) {
  44847. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  44848. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  44849. for ( let i = 0; i < textures.length; i ++ ) {
  44850. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  44851. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  44852. }
  44853. }
  44854. for ( let i = 0; i < textures.length; i ++ ) {
  44855. if ( isMRT ) {
  44856. // configure attachment for resolve
  44857. const { textureGPU } = this.get( textures[ i ] );
  44858. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44859. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  44860. }
  44861. if ( renderContext.scissor ) {
  44862. const { x, y, width, height } = renderContext.scissorValue;
  44863. const viewY = renderContext.height - height - y;
  44864. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  44865. } else {
  44866. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  44867. }
  44868. }
  44869. if ( isMRT ) {
  44870. // restore attachments
  44871. for ( let i = 0; i < textures.length; i ++ ) {
  44872. const { textureGPU } = this.get( textures[ i ] );
  44873. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44874. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  44875. }
  44876. }
  44877. if ( this._supportsInvalidateFramebuffer === true ) {
  44878. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  44879. }
  44880. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  44881. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  44882. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44883. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  44884. }
  44885. }
  44886. if ( previousContext !== null ) {
  44887. this._setFramebuffer( previousContext );
  44888. if ( previousContext.viewport ) {
  44889. this.updateViewport( previousContext );
  44890. } else {
  44891. const { width, height } = this.getDrawingBufferSize();
  44892. state.viewport( 0, 0, width, height );
  44893. }
  44894. }
  44895. this.prepareTimestampBuffer( renderContext );
  44896. }
  44897. /**
  44898. * This method processes the result of occlusion queries and writes it
  44899. * into render context data.
  44900. *
  44901. * @async
  44902. * @param {RenderContext} renderContext - The render context.
  44903. */
  44904. resolveOccludedAsync( renderContext ) {
  44905. const renderContextData = this.get( renderContext );
  44906. // handle occlusion query results
  44907. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  44908. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  44909. const occluded = new WeakSet();
  44910. const { gl } = this;
  44911. renderContextData.currentOcclusionQueryObjects = null;
  44912. renderContextData.currentOcclusionQueries = null;
  44913. const check = () => {
  44914. let completed = 0;
  44915. // check all queries and requeue as appropriate
  44916. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  44917. const query = currentOcclusionQueries[ i ];
  44918. if ( query === null ) continue;
  44919. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  44920. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  44921. currentOcclusionQueries[ i ] = null;
  44922. gl.deleteQuery( query );
  44923. completed ++;
  44924. }
  44925. }
  44926. if ( completed < currentOcclusionQueries.length ) {
  44927. requestAnimationFrame( check );
  44928. } else {
  44929. renderContextData.occluded = occluded;
  44930. }
  44931. };
  44932. check();
  44933. }
  44934. }
  44935. /**
  44936. * Returns `true` if the given 3D object is fully occluded by other
  44937. * 3D objects in the scene.
  44938. *
  44939. * @param {RenderContext} renderContext - The render context.
  44940. * @param {Object3D} object - The 3D object to test.
  44941. * @return {boolean} Whether the 3D object is fully occluded or not.
  44942. */
  44943. isOccluded( renderContext, object ) {
  44944. const renderContextData = this.get( renderContext );
  44945. return renderContextData.occluded && renderContextData.occluded.has( object );
  44946. }
  44947. /**
  44948. * Updates the viewport with the values from the given render context.
  44949. *
  44950. * @param {RenderContext} renderContext - The render context.
  44951. */
  44952. updateViewport( renderContext ) {
  44953. const { state } = this;
  44954. const { x, y, width, height } = renderContext.viewportValue;
  44955. state.viewport( x, renderContext.height - height - y, width, height );
  44956. }
  44957. /**
  44958. * Defines the scissor test.
  44959. *
  44960. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44961. */
  44962. setScissorTest( boolean ) {
  44963. const state = this.state;
  44964. state.setScissorTest( boolean );
  44965. }
  44966. /**
  44967. * Returns the clear color and alpha into a single
  44968. * color object.
  44969. *
  44970. * @return {Color4} The clear color.
  44971. */
  44972. getClearColor() {
  44973. const clearColor = super.getClearColor();
  44974. // Since the canvas is always created with alpha: true,
  44975. // WebGL must always premultiply the clear color.
  44976. clearColor.r *= clearColor.a;
  44977. clearColor.g *= clearColor.a;
  44978. clearColor.b *= clearColor.a;
  44979. return clearColor;
  44980. }
  44981. /**
  44982. * Performs a clear operation.
  44983. *
  44984. * @param {boolean} color - Whether the color buffer should be cleared or not.
  44985. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  44986. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  44987. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  44988. * @param {boolean} [setFrameBuffer=true] - TODO.
  44989. */
  44990. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  44991. const { gl, renderer } = this;
  44992. if ( descriptor === null ) {
  44993. const clearColor = this.getClearColor();
  44994. descriptor = {
  44995. textures: null,
  44996. clearColorValue: clearColor
  44997. };
  44998. }
  44999. //
  45000. let clear = 0;
  45001. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  45002. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  45003. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  45004. if ( clear !== 0 ) {
  45005. let clearColor;
  45006. if ( descriptor.clearColorValue ) {
  45007. clearColor = descriptor.clearColorValue;
  45008. } else {
  45009. clearColor = this.getClearColor();
  45010. }
  45011. const clearDepth = renderer.getClearDepth();
  45012. const clearStencil = renderer.getClearStencil();
  45013. if ( depth ) this.state.setDepthMask( true );
  45014. if ( descriptor.textures === null ) {
  45015. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  45016. gl.clear( clear );
  45017. } else {
  45018. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  45019. if ( color ) {
  45020. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  45021. if ( i === 0 ) {
  45022. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  45023. } else {
  45024. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  45025. }
  45026. }
  45027. }
  45028. if ( depth && stencil ) {
  45029. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  45030. } else if ( depth ) {
  45031. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  45032. } else if ( stencil ) {
  45033. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  45034. }
  45035. }
  45036. }
  45037. }
  45038. /**
  45039. * This method is executed at the beginning of a compute call and
  45040. * prepares the state for upcoming compute tasks.
  45041. *
  45042. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45043. */
  45044. beginCompute( computeGroup ) {
  45045. const { state, gl } = this;
  45046. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  45047. this.initTimestampQuery( computeGroup );
  45048. }
  45049. /**
  45050. * Executes a compute command for the given compute node.
  45051. *
  45052. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45053. * @param {Node} computeNode - The compute node.
  45054. * @param {Array<BindGroup>} bindings - The bindings.
  45055. * @param {ComputePipeline} pipeline - The compute pipeline.
  45056. * @param {number|null} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  45057. */
  45058. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  45059. const { state, gl } = this;
  45060. if ( this.discard === false ) {
  45061. // required here to handle async behaviour of render.compute()
  45062. gl.enable( gl.RASTERIZER_DISCARD );
  45063. this.discard = true;
  45064. }
  45065. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  45066. const vaoKey = this._getVaoKey( attributes );
  45067. const vaoGPU = this.vaoCache[ vaoKey ];
  45068. if ( vaoGPU === undefined ) {
  45069. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  45070. } else {
  45071. state.setVertexState( vaoGPU );
  45072. }
  45073. state.useProgram( programGPU );
  45074. this._bindUniforms( bindings );
  45075. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  45076. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  45077. gl.beginTransformFeedback( gl.POINTS );
  45078. count = ( count !== null ) ? count : computeNode.count;
  45079. if ( Array.isArray( count ) ) {
  45080. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  45081. count = count[ 0 ];
  45082. }
  45083. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  45084. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  45085. } else {
  45086. gl.drawArrays( gl.POINTS, 0, count );
  45087. }
  45088. gl.endTransformFeedback();
  45089. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  45090. // switch active buffers
  45091. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  45092. const dualAttributeData = transformBuffers[ i ];
  45093. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  45094. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  45095. }
  45096. dualAttributeData.switchBuffers();
  45097. }
  45098. }
  45099. /**
  45100. * This method is executed at the end of a compute call and
  45101. * finalizes work after compute tasks.
  45102. *
  45103. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45104. */
  45105. finishCompute( computeGroup ) {
  45106. const gl = this.gl;
  45107. this.discard = false;
  45108. gl.disable( gl.RASTERIZER_DISCARD );
  45109. this.prepareTimestampBuffer( computeGroup );
  45110. if ( this._currentContext ) {
  45111. this._setFramebuffer( this._currentContext );
  45112. }
  45113. }
  45114. /**
  45115. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  45116. *
  45117. * @param {RenderContext} renderContext - The render context.
  45118. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  45119. *
  45120. * @private
  45121. */
  45122. _isRenderCameraDepthArray( renderContext ) {
  45123. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  45124. }
  45125. /**
  45126. * Executes a draw command for the given render object.
  45127. *
  45128. * @param {RenderObject} renderObject - The render object to draw.
  45129. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45130. */
  45131. draw( renderObject/*, info*/ ) {
  45132. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  45133. const { programGPU } = this.get( pipeline );
  45134. const { gl, state } = this;
  45135. const contextData = this.get( context );
  45136. const drawParams = renderObject.getDrawParameters();
  45137. if ( drawParams === null ) return;
  45138. //
  45139. this._bindUniforms( renderObject.getBindings() );
  45140. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  45141. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  45142. state.useProgram( programGPU );
  45143. // vertex state
  45144. const attributes = renderObject.getAttributes();
  45145. const attributesData = this.get( attributes );
  45146. let vaoGPU = attributesData.vaoGPU;
  45147. if ( vaoGPU === undefined ) {
  45148. const vaoKey = this._getVaoKey( attributes );
  45149. vaoGPU = this.vaoCache[ vaoKey ];
  45150. if ( vaoGPU === undefined ) {
  45151. vaoGPU = this._createVao( attributes );
  45152. this.vaoCache[ vaoKey ] = vaoGPU;
  45153. attributesData.vaoGPU = vaoGPU;
  45154. }
  45155. }
  45156. const index = renderObject.getIndex();
  45157. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  45158. state.setVertexState( vaoGPU, indexGPU );
  45159. //
  45160. const lastObject = contextData.lastOcclusionObject;
  45161. if ( lastObject !== object && lastObject !== undefined ) {
  45162. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  45163. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  45164. contextData.occlusionQueryIndex ++;
  45165. }
  45166. if ( object.occlusionTest === true ) {
  45167. const query = gl.createQuery();
  45168. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  45169. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  45170. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  45171. }
  45172. contextData.lastOcclusionObject = object;
  45173. }
  45174. //
  45175. const renderer = this.bufferRenderer;
  45176. if ( object.isPoints ) renderer.mode = gl.POINTS;
  45177. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  45178. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  45179. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  45180. else {
  45181. if ( material.wireframe === true ) {
  45182. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  45183. renderer.mode = gl.LINES;
  45184. } else {
  45185. renderer.mode = gl.TRIANGLES;
  45186. }
  45187. }
  45188. //
  45189. const { vertexCount, instanceCount } = drawParams;
  45190. let { firstVertex } = drawParams;
  45191. renderer.object = object;
  45192. if ( index !== null ) {
  45193. firstVertex *= index.array.BYTES_PER_ELEMENT;
  45194. const indexData = this.get( index );
  45195. renderer.index = index.count;
  45196. renderer.type = indexData.type;
  45197. } else {
  45198. renderer.index = 0;
  45199. }
  45200. const draw = () => {
  45201. if ( object.isBatchedMesh ) {
  45202. if ( object._multiDrawInstances !== null ) {
  45203. // @deprecated, r174
  45204. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  45205. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  45206. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  45207. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  45208. } else {
  45209. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  45210. }
  45211. } else if ( instanceCount > 1 ) {
  45212. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  45213. } else {
  45214. renderer.render( firstVertex, vertexCount );
  45215. }
  45216. };
  45217. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  45218. const cameraData = this.get( renderObject.camera );
  45219. const cameras = renderObject.camera.cameras;
  45220. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  45221. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  45222. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  45223. const indexesGPU = [];
  45224. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45225. const bufferGPU = gl.createBuffer();
  45226. data[ 0 ] = i;
  45227. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  45228. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  45229. indexesGPU.push( bufferGPU );
  45230. }
  45231. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  45232. }
  45233. const cameraIndexData = this.get( cameraIndex );
  45234. const pixelRatio = this.renderer.getPixelRatio();
  45235. const renderTarget = this._currentContext.renderTarget;
  45236. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  45237. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  45238. if ( isRenderCameraDepthArray ) {
  45239. // Clear the depth texture
  45240. const textureData = this.get( renderTarget.depthTexture );
  45241. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  45242. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  45243. const { stencilBuffer } = renderTarget;
  45244. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45245. this.renderer._activeCubeFace = i;
  45246. this._currentContext.activeCubeFace = i;
  45247. this._setFramebuffer( this._currentContext );
  45248. this.clear( false, true, stencilBuffer, this._currentContext, false );
  45249. }
  45250. this.renderer._activeCubeFace = prevActiveCubeFace;
  45251. this._currentContext.activeCubeFace = prevActiveCubeFace;
  45252. }
  45253. }
  45254. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45255. const subCamera = cameras[ i ];
  45256. if ( object.layers.test( subCamera.layers ) ) {
  45257. if ( isRenderCameraDepthArray ) {
  45258. // Update the active layer
  45259. this.renderer._activeCubeFace = i;
  45260. this._currentContext.activeCubeFace = i;
  45261. this._setFramebuffer( this._currentContext );
  45262. }
  45263. const vp = subCamera.viewport;
  45264. if ( vp !== undefined ) {
  45265. const x = vp.x * pixelRatio;
  45266. const y = vp.y * pixelRatio;
  45267. const width = vp.width * pixelRatio;
  45268. const height = vp.height * pixelRatio;
  45269. state.viewport(
  45270. Math.floor( x ),
  45271. Math.floor( renderObject.context.height - height - y ),
  45272. Math.floor( width ),
  45273. Math.floor( height )
  45274. );
  45275. }
  45276. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  45277. draw();
  45278. }
  45279. this._currentContext.activeCubeFace = prevActiveCubeFace;
  45280. this.renderer._activeCubeFace = prevActiveCubeFace;
  45281. }
  45282. } else {
  45283. draw();
  45284. }
  45285. }
  45286. /**
  45287. * Explain why always null is returned.
  45288. *
  45289. * @param {RenderObject} renderObject - The render object.
  45290. * @return {boolean} Whether the render pipeline requires an update or not.
  45291. */
  45292. needsRenderUpdate( /*renderObject*/ ) {
  45293. return false;
  45294. }
  45295. /**
  45296. * Explain why no cache key is computed.
  45297. *
  45298. * @param {RenderObject} renderObject - The render object.
  45299. * @return {string} The cache key.
  45300. */
  45301. getRenderCacheKey( /*renderObject*/ ) {
  45302. return '';
  45303. }
  45304. // textures
  45305. /**
  45306. * Creates a default texture for the given texture that can be used
  45307. * as a placeholder until the actual texture is ready for usage.
  45308. *
  45309. * @param {Texture} texture - The texture to create a default texture for.
  45310. */
  45311. createDefaultTexture( texture ) {
  45312. this.textureUtils.createDefaultTexture( texture );
  45313. }
  45314. /**
  45315. * Defines a texture on the GPU for the given texture object.
  45316. *
  45317. * @param {Texture} texture - The texture.
  45318. * @param {Object} [options={}] - Optional configuration parameter.
  45319. */
  45320. createTexture( texture, options ) {
  45321. this.textureUtils.createTexture( texture, options );
  45322. }
  45323. /**
  45324. * Uploads the updated texture data to the GPU.
  45325. *
  45326. * @param {Texture} texture - The texture.
  45327. * @param {Object} [options={}] - Optional configuration parameter.
  45328. */
  45329. updateTexture( texture, options ) {
  45330. this.textureUtils.updateTexture( texture, options );
  45331. }
  45332. /**
  45333. * Generates mipmaps for the given texture.
  45334. *
  45335. * @param {Texture} texture - The texture.
  45336. */
  45337. generateMipmaps( texture ) {
  45338. this.textureUtils.generateMipmaps( texture );
  45339. }
  45340. /**
  45341. * Destroys the GPU data for the given texture object.
  45342. *
  45343. * @param {Texture} texture - The texture.
  45344. */
  45345. destroyTexture( texture ) {
  45346. this.textureUtils.destroyTexture( texture );
  45347. }
  45348. /**
  45349. * Returns texture data as a typed array.
  45350. *
  45351. * @async
  45352. * @param {Texture} texture - The texture to copy.
  45353. * @param {number} x - The x coordinate of the copy origin.
  45354. * @param {number} y - The y coordinate of the copy origin.
  45355. * @param {number} width - The width of the copy.
  45356. * @param {number} height - The height of the copy.
  45357. * @param {number} faceIndex - The face index.
  45358. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45359. */
  45360. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45361. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  45362. }
  45363. /**
  45364. * This method does nothing since WebGL 2 has no concept of samplers.
  45365. *
  45366. * @param {Texture} texture - The texture to create the sampler for.
  45367. */
  45368. createSampler( /*texture*/ ) {
  45369. //console.warn( 'Abstract class.' );
  45370. }
  45371. /**
  45372. * This method does nothing since WebGL 2 has no concept of samplers.
  45373. *
  45374. * @param {Texture} texture - The texture to destroy the sampler for.
  45375. */
  45376. destroySampler( /*texture*/ ) {}
  45377. // node builder
  45378. /**
  45379. * Returns a node builder for the given render object.
  45380. *
  45381. * @param {RenderObject} object - The render object.
  45382. * @param {Renderer} renderer - The renderer.
  45383. * @return {GLSLNodeBuilder} The node builder.
  45384. */
  45385. createNodeBuilder( object, renderer ) {
  45386. return new GLSLNodeBuilder( object, renderer );
  45387. }
  45388. // program
  45389. /**
  45390. * Creates a shader program from the given programmable stage.
  45391. *
  45392. * @param {ProgrammableStage} program - The programmable stage.
  45393. */
  45394. createProgram( program ) {
  45395. const gl = this.gl;
  45396. const { stage, code } = program;
  45397. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  45398. gl.shaderSource( shader, code );
  45399. gl.compileShader( shader );
  45400. this.set( program, {
  45401. shaderGPU: shader
  45402. } );
  45403. }
  45404. /**
  45405. * Destroys the shader program of the given programmable stage.
  45406. *
  45407. * @param {ProgrammableStage} program - The programmable stage.
  45408. */
  45409. destroyProgram( program ) {
  45410. this.delete( program );
  45411. }
  45412. /**
  45413. * Creates a render pipeline for the given render object.
  45414. *
  45415. * @param {RenderObject} renderObject - The render object.
  45416. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45417. */
  45418. createRenderPipeline( renderObject, promises ) {
  45419. const gl = this.gl;
  45420. const pipeline = renderObject.pipeline;
  45421. // Program
  45422. const { fragmentProgram, vertexProgram } = pipeline;
  45423. const programGPU = gl.createProgram();
  45424. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  45425. const vertexShader = this.get( vertexProgram ).shaderGPU;
  45426. gl.attachShader( programGPU, fragmentShader );
  45427. gl.attachShader( programGPU, vertexShader );
  45428. gl.linkProgram( programGPU );
  45429. this.set( pipeline, {
  45430. programGPU,
  45431. fragmentShader,
  45432. vertexShader
  45433. } );
  45434. if ( promises !== null && this.parallel ) {
  45435. const p = new Promise( ( resolve /*, reject*/ ) => {
  45436. const parallel = this.parallel;
  45437. const checkStatus = () => {
  45438. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  45439. this._completeCompile( renderObject, pipeline );
  45440. resolve();
  45441. } else {
  45442. requestAnimationFrame( checkStatus );
  45443. }
  45444. };
  45445. checkStatus();
  45446. } );
  45447. promises.push( p );
  45448. return;
  45449. }
  45450. this._completeCompile( renderObject, pipeline );
  45451. }
  45452. /**
  45453. * Formats the source code of error messages.
  45454. *
  45455. * @private
  45456. * @param {string} string - The code.
  45457. * @param {number} errorLine - The error line.
  45458. * @return {string} The formatted code.
  45459. */
  45460. _handleSource( string, errorLine ) {
  45461. const lines = string.split( '\n' );
  45462. const lines2 = [];
  45463. const from = Math.max( errorLine - 6, 0 );
  45464. const to = Math.min( errorLine + 6, lines.length );
  45465. for ( let i = from; i < to; i ++ ) {
  45466. const line = i + 1;
  45467. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  45468. }
  45469. return lines2.join( '\n' );
  45470. }
  45471. /**
  45472. * Gets the shader compilation errors from the info log.
  45473. *
  45474. * @private
  45475. * @param {WebGL2RenderingContext} gl - The rendering context.
  45476. * @param {WebGLShader} shader - The WebGL shader object.
  45477. * @param {string} type - The shader type.
  45478. * @return {string} The shader errors.
  45479. */
  45480. _getShaderErrors( gl, shader, type ) {
  45481. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  45482. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  45483. const errors = shaderInfoLog.trim();
  45484. if ( status && errors === '' ) return '';
  45485. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  45486. if ( errorMatches ) {
  45487. const errorLine = parseInt( errorMatches[ 1 ] );
  45488. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  45489. } else {
  45490. return errors;
  45491. }
  45492. }
  45493. /**
  45494. * Logs shader compilation errors.
  45495. *
  45496. * @private
  45497. * @param {WebGLProgram} programGPU - The WebGL program.
  45498. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  45499. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  45500. */
  45501. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  45502. if ( this.renderer.debug.checkShaderErrors ) {
  45503. const gl = this.gl;
  45504. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  45505. const programLog = programInfoLog.trim();
  45506. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  45507. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  45508. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  45509. } else {
  45510. // default error reporting
  45511. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  45512. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  45513. console.error(
  45514. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  45515. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  45516. 'Program Info Log: ' + programLog + '\n' +
  45517. vertexErrors + '\n' +
  45518. fragmentErrors
  45519. );
  45520. }
  45521. } else if ( programLog !== '' ) {
  45522. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  45523. }
  45524. }
  45525. }
  45526. /**
  45527. * Completes the shader program setup for the given render object.
  45528. *
  45529. * @private
  45530. * @param {RenderObject} renderObject - The render object.
  45531. * @param {RenderPipeline} pipeline - The render pipeline.
  45532. */
  45533. _completeCompile( renderObject, pipeline ) {
  45534. const { state, gl } = this;
  45535. const pipelineData = this.get( pipeline );
  45536. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  45537. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  45538. this._logProgramError( programGPU, fragmentShader, vertexShader );
  45539. }
  45540. state.useProgram( programGPU );
  45541. // Bindings
  45542. const bindings = renderObject.getBindings();
  45543. this._setupBindings( bindings, programGPU );
  45544. //
  45545. this.set( pipeline, {
  45546. programGPU
  45547. } );
  45548. }
  45549. /**
  45550. * Creates a compute pipeline for the given compute node.
  45551. *
  45552. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45553. * @param {Array<BindGroup>} bindings - The bindings.
  45554. */
  45555. createComputePipeline( computePipeline, bindings ) {
  45556. const { state, gl } = this;
  45557. // Program
  45558. const fragmentProgram = {
  45559. stage: 'fragment',
  45560. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  45561. };
  45562. this.createProgram( fragmentProgram );
  45563. const { computeProgram } = computePipeline;
  45564. const programGPU = gl.createProgram();
  45565. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  45566. const vertexShader = this.get( computeProgram ).shaderGPU;
  45567. const transforms = computeProgram.transforms;
  45568. const transformVaryingNames = [];
  45569. const transformAttributeNodes = [];
  45570. for ( let i = 0; i < transforms.length; i ++ ) {
  45571. const transform = transforms[ i ];
  45572. transformVaryingNames.push( transform.varyingName );
  45573. transformAttributeNodes.push( transform.attributeNode );
  45574. }
  45575. gl.attachShader( programGPU, fragmentShader );
  45576. gl.attachShader( programGPU, vertexShader );
  45577. gl.transformFeedbackVaryings(
  45578. programGPU,
  45579. transformVaryingNames,
  45580. gl.SEPARATE_ATTRIBS
  45581. );
  45582. gl.linkProgram( programGPU );
  45583. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  45584. this._logProgramError( programGPU, fragmentShader, vertexShader );
  45585. }
  45586. state.useProgram( programGPU );
  45587. // Bindings
  45588. this._setupBindings( bindings, programGPU );
  45589. const attributeNodes = computeProgram.attributes;
  45590. const attributes = [];
  45591. const transformBuffers = [];
  45592. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  45593. const attribute = attributeNodes[ i ].node.attribute;
  45594. attributes.push( attribute );
  45595. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45596. }
  45597. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  45598. const attribute = transformAttributeNodes[ i ].attribute;
  45599. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45600. const attributeData = this.get( attribute );
  45601. transformBuffers.push( attributeData );
  45602. }
  45603. //
  45604. this.set( computePipeline, {
  45605. programGPU,
  45606. transformBuffers,
  45607. attributes
  45608. } );
  45609. }
  45610. /**
  45611. * Creates bindings from the given bind group definition.
  45612. *
  45613. * @param {BindGroup} bindGroup - The bind group.
  45614. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45615. * @param {number} cacheIndex - The cache index.
  45616. * @param {number} version - The version.
  45617. */
  45618. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  45619. if ( this._knownBindings.has( bindings ) === false ) {
  45620. this._knownBindings.add( bindings );
  45621. let uniformBuffers = 0;
  45622. let textures = 0;
  45623. for ( const bindGroup of bindings ) {
  45624. this.set( bindGroup, {
  45625. textures: textures,
  45626. uniformBuffers: uniformBuffers
  45627. } );
  45628. for ( const binding of bindGroup.bindings ) {
  45629. if ( binding.isUniformBuffer ) uniformBuffers ++;
  45630. if ( binding.isSampledTexture ) textures ++;
  45631. }
  45632. }
  45633. }
  45634. this.updateBindings( bindGroup, bindings );
  45635. }
  45636. /**
  45637. * Updates the given bind group definition.
  45638. *
  45639. * @param {BindGroup} bindGroup - The bind group.
  45640. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45641. * @param {number} cacheIndex - The cache index.
  45642. * @param {number} version - The version.
  45643. */
  45644. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  45645. const { gl } = this;
  45646. const bindGroupData = this.get( bindGroup );
  45647. let i = bindGroupData.uniformBuffers;
  45648. let t = bindGroupData.textures;
  45649. for ( const binding of bindGroup.bindings ) {
  45650. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45651. const data = binding.buffer;
  45652. const bufferGPU = gl.createBuffer();
  45653. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  45654. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  45655. this.set( binding, {
  45656. index: i ++,
  45657. bufferGPU
  45658. } );
  45659. } else if ( binding.isSampledTexture ) {
  45660. const { textureGPU, glTextureType } = this.get( binding.texture );
  45661. this.set( binding, {
  45662. index: t ++,
  45663. textureGPU,
  45664. glTextureType
  45665. } );
  45666. }
  45667. }
  45668. }
  45669. /**
  45670. * Updates a buffer binding.
  45671. *
  45672. * @param {Buffer} binding - The buffer binding to update.
  45673. */
  45674. updateBinding( binding ) {
  45675. const gl = this.gl;
  45676. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45677. const bindingData = this.get( binding );
  45678. const bufferGPU = bindingData.bufferGPU;
  45679. const data = binding.buffer;
  45680. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  45681. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  45682. }
  45683. }
  45684. // attributes
  45685. /**
  45686. * Creates the GPU buffer of an indexed shader attribute.
  45687. *
  45688. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  45689. */
  45690. createIndexAttribute( attribute ) {
  45691. const gl = this.gl;
  45692. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  45693. }
  45694. /**
  45695. * Creates the GPU buffer of a shader attribute.
  45696. *
  45697. * @param {BufferAttribute} attribute - The buffer attribute.
  45698. */
  45699. createAttribute( attribute ) {
  45700. if ( this.has( attribute ) ) return;
  45701. const gl = this.gl;
  45702. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45703. }
  45704. /**
  45705. * Creates the GPU buffer of a storage attribute.
  45706. *
  45707. * @param {BufferAttribute} attribute - The buffer attribute.
  45708. */
  45709. createStorageAttribute( attribute ) {
  45710. if ( this.has( attribute ) ) return;
  45711. const gl = this.gl;
  45712. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45713. }
  45714. /**
  45715. * Updates the GPU buffer of a shader attribute.
  45716. *
  45717. * @param {BufferAttribute} attribute - The buffer attribute to update.
  45718. */
  45719. updateAttribute( attribute ) {
  45720. this.attributeUtils.updateAttribute( attribute );
  45721. }
  45722. /**
  45723. * Destroys the GPU buffer of a shader attribute.
  45724. *
  45725. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  45726. */
  45727. destroyAttribute( attribute ) {
  45728. this.attributeUtils.destroyAttribute( attribute );
  45729. }
  45730. /**
  45731. * Checks if the given feature is supported by the backend.
  45732. *
  45733. * @param {string} name - The feature's name.
  45734. * @return {boolean} Whether the feature is supported or not.
  45735. */
  45736. hasFeature( name ) {
  45737. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  45738. const extensions = this.extensions;
  45739. for ( let i = 0; i < keysMatching.length; i ++ ) {
  45740. if ( extensions.has( keysMatching[ i ] ) ) return true;
  45741. }
  45742. return false;
  45743. }
  45744. /**
  45745. * Returns the maximum anisotropy texture filtering value.
  45746. *
  45747. * @return {number} The maximum anisotropy texture filtering value.
  45748. */
  45749. getMaxAnisotropy() {
  45750. return this.capabilities.getMaxAnisotropy();
  45751. }
  45752. /**
  45753. * Copies data of the given source texture to the given destination texture.
  45754. *
  45755. * @param {Texture} srcTexture - The source texture.
  45756. * @param {Texture} dstTexture - The destination texture.
  45757. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45758. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45759. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45760. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45761. */
  45762. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  45763. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  45764. }
  45765. /**
  45766. * Copies the current bound framebuffer to the given texture.
  45767. *
  45768. * @param {Texture} texture - The destination texture.
  45769. * @param {RenderContext} renderContext - The render context.
  45770. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45771. */
  45772. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45773. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  45774. }
  45775. /**
  45776. * Configures the active framebuffer from the given render context.
  45777. *
  45778. * @private
  45779. * @param {RenderContext} descriptor - The render context.
  45780. */
  45781. _setFramebuffer( descriptor ) {
  45782. const { gl, state } = this;
  45783. let currentFrameBuffer = null;
  45784. if ( descriptor.textures !== null ) {
  45785. const renderTarget = descriptor.renderTarget;
  45786. const renderTargetContextData = this.get( renderTarget );
  45787. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  45788. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  45789. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  45790. const isRenderTargetArray = renderTarget.depth > 1;
  45791. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  45792. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  45793. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  45794. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  45795. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  45796. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  45797. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  45798. const cacheKey = getCacheKey( descriptor );
  45799. let fb;
  45800. if ( isCube ) {
  45801. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  45802. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  45803. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  45804. fb = this._xrFramebuffer;
  45805. } else {
  45806. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  45807. fb = renderTargetContextData.framebuffers[ cacheKey ];
  45808. }
  45809. if ( fb === undefined ) {
  45810. fb = gl.createFramebuffer();
  45811. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  45812. const textures = descriptor.textures;
  45813. const depthInvalidationArray = [];
  45814. if ( isCube ) {
  45815. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  45816. const { textureGPU } = this.get( textures[ 0 ] );
  45817. const cubeFace = this.renderer._activeCubeFace;
  45818. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  45819. } else {
  45820. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  45821. for ( let i = 0; i < textures.length; i ++ ) {
  45822. const texture = textures[ i ];
  45823. const textureData = this.get( texture );
  45824. textureData.renderTarget = descriptor.renderTarget;
  45825. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  45826. const attachment = gl.COLOR_ATTACHMENT0 + i;
  45827. if ( renderTarget.multiview ) {
  45828. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  45829. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  45830. const layer = this.renderer._activeCubeFace;
  45831. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  45832. } else {
  45833. if ( useMultisampledRTT ) {
  45834. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45835. } else {
  45836. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45837. }
  45838. }
  45839. }
  45840. }
  45841. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45842. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  45843. const renderbuffer = gl.createRenderbuffer();
  45844. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  45845. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  45846. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  45847. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  45848. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  45849. } else {
  45850. if ( descriptor.depthTexture !== null ) {
  45851. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  45852. const textureData = this.get( descriptor.depthTexture );
  45853. textureData.renderTarget = descriptor.renderTarget;
  45854. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  45855. if ( renderTarget.multiview ) {
  45856. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  45857. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  45858. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45859. } else {
  45860. if ( descriptor.depthTexture.isArrayTexture ) {
  45861. const layer = this.renderer._activeCubeFace;
  45862. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  45863. } else {
  45864. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45865. }
  45866. }
  45867. }
  45868. }
  45869. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  45870. } else {
  45871. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  45872. if ( isRenderCameraDepthArray ) {
  45873. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  45874. const layer = this.renderer._activeCubeFace;
  45875. const depthData = this.get( descriptor.depthTexture );
  45876. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45877. gl.framebufferTextureLayer(
  45878. gl.FRAMEBUFFER,
  45879. depthStyle,
  45880. depthData.textureGPU,
  45881. 0,
  45882. layer
  45883. );
  45884. }
  45885. // rebind external XR textures
  45886. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  45887. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  45888. // rebind color
  45889. const textureData = this.get( descriptor.textures[ 0 ] );
  45890. if ( renderTarget.multiview ) {
  45891. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  45892. } else if ( useMultisampledRTT ) {
  45893. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45894. } else {
  45895. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45896. }
  45897. // rebind depth
  45898. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45899. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  45900. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  45901. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  45902. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  45903. } else {
  45904. const textureData = this.get( descriptor.depthTexture );
  45905. if ( renderTarget.multiview ) {
  45906. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  45907. } else if ( useMultisampledRTT ) {
  45908. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45909. } else {
  45910. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45911. }
  45912. }
  45913. }
  45914. }
  45915. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  45916. if ( msaaFb === undefined ) {
  45917. const invalidationArray = [];
  45918. msaaFb = gl.createFramebuffer();
  45919. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  45920. const msaaRenderbuffers = [];
  45921. const textures = descriptor.textures;
  45922. for ( let i = 0; i < textures.length; i ++ ) {
  45923. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  45924. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  45925. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  45926. const texture = descriptor.textures[ i ];
  45927. const textureData = this.get( texture );
  45928. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  45929. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  45930. }
  45931. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  45932. renderTargetContextData.msaaFrameBuffer = msaaFb;
  45933. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  45934. if ( depthBuffer && depthRenderbuffer === undefined ) {
  45935. depthRenderbuffer = gl.createRenderbuffer();
  45936. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  45937. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  45938. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45939. invalidationArray.push( depthStyle );
  45940. }
  45941. renderTargetContextData.invalidationArray = invalidationArray;
  45942. }
  45943. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  45944. } else {
  45945. currentFrameBuffer = fb;
  45946. }
  45947. state.drawBuffers( descriptor, fb );
  45948. }
  45949. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  45950. }
  45951. /**
  45952. * Computes the VAO key for the given index and attributes.
  45953. *
  45954. * @private
  45955. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  45956. * @return {string} The VAO key.
  45957. */
  45958. _getVaoKey( attributes ) {
  45959. let key = '';
  45960. for ( let i = 0; i < attributes.length; i ++ ) {
  45961. const attributeData = this.get( attributes[ i ] );
  45962. key += ':' + attributeData.id;
  45963. }
  45964. return key;
  45965. }
  45966. /**
  45967. * Creates a VAO from the index and attributes.
  45968. *
  45969. * @private
  45970. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  45971. * @return {Object} The VAO data.
  45972. */
  45973. _createVao( attributes ) {
  45974. const { gl } = this;
  45975. const vaoGPU = gl.createVertexArray();
  45976. gl.bindVertexArray( vaoGPU );
  45977. for ( let i = 0; i < attributes.length; i ++ ) {
  45978. const attribute = attributes[ i ];
  45979. const attributeData = this.get( attribute );
  45980. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  45981. gl.enableVertexAttribArray( i );
  45982. let stride, offset;
  45983. if ( attribute.isInterleavedBufferAttribute === true ) {
  45984. stride = attribute.data.stride * attributeData.bytesPerElement;
  45985. offset = attribute.offset * attributeData.bytesPerElement;
  45986. } else {
  45987. stride = 0;
  45988. offset = 0;
  45989. }
  45990. if ( attributeData.isInteger ) {
  45991. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  45992. } else {
  45993. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  45994. }
  45995. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  45996. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  45997. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  45998. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  45999. }
  46000. }
  46001. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  46002. return vaoGPU;
  46003. }
  46004. /**
  46005. * Creates a transform feedback from the given transform buffers.
  46006. *
  46007. * @private
  46008. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  46009. * @return {WebGLTransformFeedback} The transform feedback.
  46010. */
  46011. _getTransformFeedback( transformBuffers ) {
  46012. let key = '';
  46013. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  46014. key += ':' + transformBuffers[ i ].id;
  46015. }
  46016. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  46017. if ( transformFeedbackGPU !== undefined ) {
  46018. return transformFeedbackGPU;
  46019. }
  46020. const { gl } = this;
  46021. transformFeedbackGPU = gl.createTransformFeedback();
  46022. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  46023. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  46024. const attributeData = transformBuffers[ i ];
  46025. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  46026. }
  46027. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  46028. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  46029. return transformFeedbackGPU;
  46030. }
  46031. /**
  46032. * Setups the given bindings.
  46033. *
  46034. * @private
  46035. * @param {Array<BindGroup>} bindings - The bindings.
  46036. * @param {WebGLProgram} programGPU - The WebGL program.
  46037. */
  46038. _setupBindings( bindings, programGPU ) {
  46039. const gl = this.gl;
  46040. for ( const bindGroup of bindings ) {
  46041. for ( const binding of bindGroup.bindings ) {
  46042. const bindingData = this.get( binding );
  46043. const index = bindingData.index;
  46044. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46045. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  46046. gl.uniformBlockBinding( programGPU, location, index );
  46047. } else if ( binding.isSampledTexture ) {
  46048. const location = gl.getUniformLocation( programGPU, binding.name );
  46049. gl.uniform1i( location, index );
  46050. }
  46051. }
  46052. }
  46053. }
  46054. /**
  46055. * Binds the given uniforms.
  46056. *
  46057. * @private
  46058. * @param {Array<BindGroup>} bindings - The bindings.
  46059. */
  46060. _bindUniforms( bindings ) {
  46061. const { gl, state } = this;
  46062. for ( const bindGroup of bindings ) {
  46063. for ( const binding of bindGroup.bindings ) {
  46064. const bindingData = this.get( binding );
  46065. const index = bindingData.index;
  46066. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46067. // TODO USE bindBufferRange to group multiple uniform buffers
  46068. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  46069. } else if ( binding.isSampledTexture ) {
  46070. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  46071. }
  46072. }
  46073. }
  46074. }
  46075. /**
  46076. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  46077. * should be used when MSAA is enabled.
  46078. *
  46079. * @private
  46080. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  46081. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  46082. */
  46083. _useMultisampledExtension( renderTarget ) {
  46084. if ( renderTarget.multiview === true ) {
  46085. return true;
  46086. }
  46087. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  46088. }
  46089. /**
  46090. * Frees internal resources.
  46091. */
  46092. dispose() {
  46093. const extension = this.extensions.get( 'WEBGL_lose_context' );
  46094. if ( extension ) extension.loseContext();
  46095. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  46096. }
  46097. }
  46098. const GPUPrimitiveTopology = {
  46099. PointList: 'point-list',
  46100. LineList: 'line-list',
  46101. LineStrip: 'line-strip',
  46102. TriangleList: 'triangle-list',
  46103. TriangleStrip: 'triangle-strip',
  46104. };
  46105. const GPUCompareFunction = {
  46106. Never: 'never',
  46107. Less: 'less',
  46108. Equal: 'equal',
  46109. LessEqual: 'less-equal',
  46110. Greater: 'greater',
  46111. NotEqual: 'not-equal',
  46112. GreaterEqual: 'greater-equal',
  46113. Always: 'always'
  46114. };
  46115. const GPUStoreOp = {
  46116. Store: 'store'};
  46117. const GPULoadOp = {
  46118. Load: 'load',
  46119. Clear: 'clear'
  46120. };
  46121. const GPUFrontFace = {
  46122. CCW: 'ccw'};
  46123. const GPUCullMode = {
  46124. None: 'none',
  46125. Front: 'front',
  46126. Back: 'back'
  46127. };
  46128. const GPUIndexFormat = {
  46129. Uint16: 'uint16',
  46130. Uint32: 'uint32'
  46131. };
  46132. const GPUTextureFormat = {
  46133. // 8-bit formats
  46134. R8Unorm: 'r8unorm',
  46135. R8Snorm: 'r8snorm',
  46136. R8Uint: 'r8uint',
  46137. R8Sint: 'r8sint',
  46138. // 16-bit formats
  46139. R16Uint: 'r16uint',
  46140. R16Sint: 'r16sint',
  46141. R16Float: 'r16float',
  46142. RG8Unorm: 'rg8unorm',
  46143. RG8Snorm: 'rg8snorm',
  46144. RG8Uint: 'rg8uint',
  46145. RG8Sint: 'rg8sint',
  46146. // 32-bit formats
  46147. R32Uint: 'r32uint',
  46148. R32Sint: 'r32sint',
  46149. R32Float: 'r32float',
  46150. RG16Uint: 'rg16uint',
  46151. RG16Sint: 'rg16sint',
  46152. RG16Float: 'rg16float',
  46153. RGBA8Unorm: 'rgba8unorm',
  46154. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  46155. RGBA8Snorm: 'rgba8snorm',
  46156. RGBA8Uint: 'rgba8uint',
  46157. RGBA8Sint: 'rgba8sint',
  46158. BGRA8Unorm: 'bgra8unorm',
  46159. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  46160. // Packed 32-bit formats
  46161. RGB9E5UFloat: 'rgb9e5ufloat',
  46162. RGB10A2Unorm: 'rgb10a2unorm',
  46163. RG11B10UFloat: 'rgb10a2unorm',
  46164. // 64-bit formats
  46165. RG32Uint: 'rg32uint',
  46166. RG32Sint: 'rg32sint',
  46167. RG32Float: 'rg32float',
  46168. RGBA16Uint: 'rgba16uint',
  46169. RGBA16Sint: 'rgba16sint',
  46170. RGBA16Float: 'rgba16float',
  46171. // 128-bit formats
  46172. RGBA32Uint: 'rgba32uint',
  46173. RGBA32Sint: 'rgba32sint',
  46174. RGBA32Float: 'rgba32float',
  46175. Depth16Unorm: 'depth16unorm',
  46176. Depth24Plus: 'depth24plus',
  46177. Depth24PlusStencil8: 'depth24plus-stencil8',
  46178. Depth32Float: 'depth32float',
  46179. // 'depth32float-stencil8' extension
  46180. Depth32FloatStencil8: 'depth32float-stencil8',
  46181. // BC compressed formats usable if 'texture-compression-bc' is both
  46182. // supported by the device/user agent and enabled in requestDevice.
  46183. BC1RGBAUnorm: 'bc1-rgba-unorm',
  46184. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  46185. BC2RGBAUnorm: 'bc2-rgba-unorm',
  46186. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  46187. BC3RGBAUnorm: 'bc3-rgba-unorm',
  46188. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  46189. BC4RUnorm: 'bc4-r-unorm',
  46190. BC4RSnorm: 'bc4-r-snorm',
  46191. BC5RGUnorm: 'bc5-rg-unorm',
  46192. BC5RGSnorm: 'bc5-rg-snorm',
  46193. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  46194. BC6HRGBFloat: 'bc6h-rgb-float',
  46195. BC7RGBAUnorm: 'bc7-rgba-unorm',
  46196. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  46197. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  46198. // supported by the device/user agent and enabled in requestDevice.
  46199. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  46200. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  46201. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  46202. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  46203. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  46204. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  46205. EACR11Unorm: 'eac-r11unorm',
  46206. EACR11Snorm: 'eac-r11snorm',
  46207. EACRG11Unorm: 'eac-rg11unorm',
  46208. EACRG11Snorm: 'eac-rg11snorm',
  46209. // ASTC compressed formats usable if 'texture-compression-astc' is both
  46210. // supported by the device/user agent and enabled in requestDevice.
  46211. ASTC4x4Unorm: 'astc-4x4-unorm',
  46212. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  46213. ASTC5x4Unorm: 'astc-5x4-unorm',
  46214. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  46215. ASTC5x5Unorm: 'astc-5x5-unorm',
  46216. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  46217. ASTC6x5Unorm: 'astc-6x5-unorm',
  46218. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  46219. ASTC6x6Unorm: 'astc-6x6-unorm',
  46220. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  46221. ASTC8x5Unorm: 'astc-8x5-unorm',
  46222. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  46223. ASTC8x6Unorm: 'astc-8x6-unorm',
  46224. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  46225. ASTC8x8Unorm: 'astc-8x8-unorm',
  46226. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  46227. ASTC10x5Unorm: 'astc-10x5-unorm',
  46228. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  46229. ASTC10x6Unorm: 'astc-10x6-unorm',
  46230. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  46231. ASTC10x8Unorm: 'astc-10x8-unorm',
  46232. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  46233. ASTC10x10Unorm: 'astc-10x10-unorm',
  46234. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  46235. ASTC12x10Unorm: 'astc-12x10-unorm',
  46236. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  46237. ASTC12x12Unorm: 'astc-12x12-unorm',
  46238. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  46239. };
  46240. const GPUAddressMode = {
  46241. ClampToEdge: 'clamp-to-edge',
  46242. Repeat: 'repeat',
  46243. MirrorRepeat: 'mirror-repeat'
  46244. };
  46245. const GPUFilterMode = {
  46246. Linear: 'linear',
  46247. Nearest: 'nearest'
  46248. };
  46249. const GPUBlendFactor = {
  46250. Zero: 'zero',
  46251. One: 'one',
  46252. Src: 'src',
  46253. OneMinusSrc: 'one-minus-src',
  46254. SrcAlpha: 'src-alpha',
  46255. OneMinusSrcAlpha: 'one-minus-src-alpha',
  46256. Dst: 'dst',
  46257. OneMinusDst: 'one-minus-dst',
  46258. DstAlpha: 'dst-alpha',
  46259. OneMinusDstAlpha: 'one-minus-dst-alpha',
  46260. SrcAlphaSaturated: 'src-alpha-saturated',
  46261. Constant: 'constant',
  46262. OneMinusConstant: 'one-minus-constant'
  46263. };
  46264. const GPUBlendOperation = {
  46265. Add: 'add',
  46266. Subtract: 'subtract',
  46267. ReverseSubtract: 'reverse-subtract',
  46268. Min: 'min',
  46269. Max: 'max'
  46270. };
  46271. const GPUColorWriteFlags = {
  46272. None: 0,
  46273. All: 0xF
  46274. };
  46275. const GPUStencilOperation = {
  46276. Keep: 'keep',
  46277. Zero: 'zero',
  46278. Replace: 'replace',
  46279. Invert: 'invert',
  46280. IncrementClamp: 'increment-clamp',
  46281. DecrementClamp: 'decrement-clamp',
  46282. IncrementWrap: 'increment-wrap',
  46283. DecrementWrap: 'decrement-wrap'
  46284. };
  46285. const GPUBufferBindingType = {
  46286. Storage: 'storage',
  46287. ReadOnlyStorage: 'read-only-storage'
  46288. };
  46289. const GPUStorageTextureAccess = {
  46290. WriteOnly: 'write-only',
  46291. ReadOnly: 'read-only',
  46292. ReadWrite: 'read-write',
  46293. };
  46294. const GPUSamplerBindingType = {
  46295. NonFiltering: 'non-filtering',
  46296. Comparison: 'comparison'
  46297. };
  46298. const GPUTextureSampleType = {
  46299. Float: 'float',
  46300. UnfilterableFloat: 'unfilterable-float',
  46301. Depth: 'depth',
  46302. SInt: 'sint',
  46303. UInt: 'uint'
  46304. };
  46305. const GPUTextureDimension = {
  46306. TwoD: '2d',
  46307. ThreeD: '3d'
  46308. };
  46309. const GPUTextureViewDimension = {
  46310. TwoD: '2d',
  46311. TwoDArray: '2d-array',
  46312. Cube: 'cube',
  46313. ThreeD: '3d'
  46314. };
  46315. const GPUTextureAspect = {
  46316. All: 'all'};
  46317. const GPUInputStepMode = {
  46318. Vertex: 'vertex',
  46319. Instance: 'instance'
  46320. };
  46321. const GPUFeatureName = {
  46322. CoreFeaturesAndLimits: 'core-features-and-limits',
  46323. DepthClipControl: 'depth-clip-control',
  46324. Depth32FloatStencil8: 'depth32float-stencil8',
  46325. TextureCompressionBC: 'texture-compression-bc',
  46326. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  46327. TextureCompressionETC2: 'texture-compression-etc2',
  46328. TextureCompressionASTC: 'texture-compression-astc',
  46329. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  46330. TimestampQuery: 'timestamp-query',
  46331. IndirectFirstInstance: 'indirect-first-instance',
  46332. ShaderF16: 'shader-f16',
  46333. RG11B10UFloat: 'rg11b10ufloat-renderable',
  46334. BGRA8UNormStorage: 'bgra8unorm-storage',
  46335. Float32Filterable: 'float32-filterable',
  46336. Float32Blendable: 'float32-blendable',
  46337. ClipDistances: 'clip-distances',
  46338. DualSourceBlending: 'dual-source-blending',
  46339. Subgroups: 'subgroups',
  46340. TextureFormatsTier1: 'texture-formats-tier1',
  46341. TextureFormatsTier2: 'texture-formats-tier2'
  46342. };
  46343. /**
  46344. * A special form of sampler binding type.
  46345. * It's texture value is managed by a node object.
  46346. *
  46347. * @private
  46348. * @augments Sampler
  46349. */
  46350. class NodeSampler extends Sampler {
  46351. /**
  46352. * Constructs a new node-based sampler.
  46353. *
  46354. * @param {string} name - The samplers's name.
  46355. * @param {TextureNode} textureNode - The texture node.
  46356. * @param {UniformGroupNode} groupNode - The uniform group node.
  46357. */
  46358. constructor( name, textureNode, groupNode ) {
  46359. super( name, textureNode ? textureNode.value : null );
  46360. /**
  46361. * The texture node.
  46362. *
  46363. * @type {TextureNode}
  46364. */
  46365. this.textureNode = textureNode;
  46366. /**
  46367. * The uniform group node.
  46368. *
  46369. * @type {UniformGroupNode}
  46370. */
  46371. this.groupNode = groupNode;
  46372. }
  46373. /**
  46374. * Updates the texture value of this sampler.
  46375. */
  46376. update() {
  46377. this.texture = this.textureNode.value;
  46378. }
  46379. }
  46380. /**
  46381. * Represents a storage buffer binding type.
  46382. *
  46383. * @private
  46384. * @augments Buffer
  46385. */
  46386. class StorageBuffer extends Buffer {
  46387. /**
  46388. * Constructs a new uniform buffer.
  46389. *
  46390. * @param {string} name - The buffer's name.
  46391. * @param {BufferAttribute} attribute - The buffer attribute.
  46392. */
  46393. constructor( name, attribute ) {
  46394. super( name, attribute ? attribute.array : null );
  46395. /**
  46396. * This flag can be used for type testing.
  46397. *
  46398. * @type {BufferAttribute}
  46399. */
  46400. this.attribute = attribute;
  46401. /**
  46402. * This flag can be used for type testing.
  46403. *
  46404. * @type {boolean}
  46405. * @readonly
  46406. * @default true
  46407. */
  46408. this.isStorageBuffer = true;
  46409. }
  46410. }
  46411. let _id = 0;
  46412. /**
  46413. * A special form of storage buffer binding type.
  46414. * It's buffer value is managed by a node object.
  46415. *
  46416. * @private
  46417. * @augments StorageBuffer
  46418. */
  46419. class NodeStorageBuffer extends StorageBuffer {
  46420. /**
  46421. * Constructs a new node-based storage buffer.
  46422. *
  46423. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  46424. * @param {UniformGroupNode} groupNode - The uniform group node.
  46425. */
  46426. constructor( nodeUniform, groupNode ) {
  46427. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  46428. /**
  46429. * The node uniform.
  46430. *
  46431. * @type {StorageBufferNode}
  46432. */
  46433. this.nodeUniform = nodeUniform;
  46434. /**
  46435. * The access type.
  46436. *
  46437. * @type {string}
  46438. */
  46439. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  46440. /**
  46441. * The uniform group node.
  46442. *
  46443. * @type {UniformGroupNode}
  46444. */
  46445. this.groupNode = groupNode;
  46446. }
  46447. /**
  46448. * The storage buffer.
  46449. *
  46450. * @type {BufferAttribute}
  46451. */
  46452. get buffer() {
  46453. return this.nodeUniform.value;
  46454. }
  46455. }
  46456. /**
  46457. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  46458. *
  46459. * @private
  46460. */
  46461. class WebGPUTexturePassUtils extends DataMap {
  46462. /**
  46463. * Constructs a new utility object.
  46464. *
  46465. * @param {GPUDevice} device - The WebGPU device.
  46466. */
  46467. constructor( device ) {
  46468. super();
  46469. /**
  46470. * The WebGPU device.
  46471. *
  46472. * @type {GPUDevice}
  46473. */
  46474. this.device = device;
  46475. const mipmapVertexSource = `
  46476. struct VarysStruct {
  46477. @builtin( position ) Position: vec4<f32>,
  46478. @location( 0 ) vTex : vec2<f32>
  46479. };
  46480. @vertex
  46481. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  46482. var Varys : VarysStruct;
  46483. var pos = array< vec2<f32>, 4 >(
  46484. vec2<f32>( -1.0, 1.0 ),
  46485. vec2<f32>( 1.0, 1.0 ),
  46486. vec2<f32>( -1.0, -1.0 ),
  46487. vec2<f32>( 1.0, -1.0 )
  46488. );
  46489. var tex = array< vec2<f32>, 4 >(
  46490. vec2<f32>( 0.0, 0.0 ),
  46491. vec2<f32>( 1.0, 0.0 ),
  46492. vec2<f32>( 0.0, 1.0 ),
  46493. vec2<f32>( 1.0, 1.0 )
  46494. );
  46495. Varys.vTex = tex[ vertexIndex ];
  46496. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  46497. return Varys;
  46498. }
  46499. `;
  46500. const mipmapFragmentSource = `
  46501. @group( 0 ) @binding( 0 )
  46502. var imgSampler : sampler;
  46503. @group( 0 ) @binding( 1 )
  46504. var img : texture_2d<f32>;
  46505. @fragment
  46506. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  46507. return textureSample( img, imgSampler, vTex );
  46508. }
  46509. `;
  46510. const flipYFragmentSource = `
  46511. @group( 0 ) @binding( 0 )
  46512. var imgSampler : sampler;
  46513. @group( 0 ) @binding( 1 )
  46514. var img : texture_2d<f32>;
  46515. @fragment
  46516. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  46517. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  46518. }
  46519. `;
  46520. /**
  46521. * The mipmap GPU sampler.
  46522. *
  46523. * @type {GPUSampler}
  46524. */
  46525. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  46526. /**
  46527. * The flipY GPU sampler.
  46528. *
  46529. * @type {GPUSampler}
  46530. */
  46531. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  46532. /**
  46533. * A cache for GPU render pipelines used for copy/transfer passes.
  46534. * Every texture format requires a unique pipeline.
  46535. *
  46536. * @type {Object<string,GPURenderPipeline>}
  46537. */
  46538. this.transferPipelines = {};
  46539. /**
  46540. * A cache for GPU render pipelines used for flipY passes.
  46541. * Every texture format requires a unique pipeline.
  46542. *
  46543. * @type {Object<string,GPURenderPipeline>}
  46544. */
  46545. this.flipYPipelines = {};
  46546. /**
  46547. * The mipmap vertex shader module.
  46548. *
  46549. * @type {GPUShaderModule}
  46550. */
  46551. this.mipmapVertexShaderModule = device.createShaderModule( {
  46552. label: 'mipmapVertex',
  46553. code: mipmapVertexSource
  46554. } );
  46555. /**
  46556. * The mipmap fragment shader module.
  46557. *
  46558. * @type {GPUShaderModule}
  46559. */
  46560. this.mipmapFragmentShaderModule = device.createShaderModule( {
  46561. label: 'mipmapFragment',
  46562. code: mipmapFragmentSource
  46563. } );
  46564. /**
  46565. * The flipY fragment shader module.
  46566. *
  46567. * @type {GPUShaderModule}
  46568. */
  46569. this.flipYFragmentShaderModule = device.createShaderModule( {
  46570. label: 'flipYFragment',
  46571. code: flipYFragmentSource
  46572. } );
  46573. }
  46574. /**
  46575. * Returns a render pipeline for the internal copy render pass. The pass
  46576. * requires a unique render pipeline for each texture format.
  46577. *
  46578. * @param {string} format - The GPU texture format
  46579. * @return {GPURenderPipeline} The GPU render pipeline.
  46580. */
  46581. getTransferPipeline( format ) {
  46582. let pipeline = this.transferPipelines[ format ];
  46583. if ( pipeline === undefined ) {
  46584. pipeline = this.device.createRenderPipeline( {
  46585. label: `mipmap-${ format }`,
  46586. vertex: {
  46587. module: this.mipmapVertexShaderModule,
  46588. entryPoint: 'main'
  46589. },
  46590. fragment: {
  46591. module: this.mipmapFragmentShaderModule,
  46592. entryPoint: 'main',
  46593. targets: [ { format } ]
  46594. },
  46595. primitive: {
  46596. topology: GPUPrimitiveTopology.TriangleStrip,
  46597. stripIndexFormat: GPUIndexFormat.Uint32
  46598. },
  46599. layout: 'auto'
  46600. } );
  46601. this.transferPipelines[ format ] = pipeline;
  46602. }
  46603. return pipeline;
  46604. }
  46605. /**
  46606. * Returns a render pipeline for the flipY render pass. The pass
  46607. * requires a unique render pipeline for each texture format.
  46608. *
  46609. * @param {string} format - The GPU texture format
  46610. * @return {GPURenderPipeline} The GPU render pipeline.
  46611. */
  46612. getFlipYPipeline( format ) {
  46613. let pipeline = this.flipYPipelines[ format ];
  46614. if ( pipeline === undefined ) {
  46615. pipeline = this.device.createRenderPipeline( {
  46616. label: `flipY-${ format }`,
  46617. vertex: {
  46618. module: this.mipmapVertexShaderModule,
  46619. entryPoint: 'main'
  46620. },
  46621. fragment: {
  46622. module: this.flipYFragmentShaderModule,
  46623. entryPoint: 'main',
  46624. targets: [ { format } ]
  46625. },
  46626. primitive: {
  46627. topology: GPUPrimitiveTopology.TriangleStrip,
  46628. stripIndexFormat: GPUIndexFormat.Uint32
  46629. },
  46630. layout: 'auto'
  46631. } );
  46632. this.flipYPipelines[ format ] = pipeline;
  46633. }
  46634. return pipeline;
  46635. }
  46636. /**
  46637. * Flip the contents of the given GPU texture along its vertical axis.
  46638. *
  46639. * @param {GPUTexture} textureGPU - The GPU texture object.
  46640. * @param {Object} textureGPUDescriptor - The texture descriptor.
  46641. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  46642. */
  46643. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  46644. const format = textureGPUDescriptor.format;
  46645. const { width, height } = textureGPUDescriptor.size;
  46646. const transferPipeline = this.getTransferPipeline( format );
  46647. const flipYPipeline = this.getFlipYPipeline( format );
  46648. const tempTexture = this.device.createTexture( {
  46649. size: { width, height, depthOrArrayLayers: 1 },
  46650. format,
  46651. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  46652. } );
  46653. const srcView = textureGPU.createView( {
  46654. baseMipLevel: 0,
  46655. mipLevelCount: 1,
  46656. dimension: GPUTextureViewDimension.TwoD,
  46657. baseArrayLayer
  46658. } );
  46659. const dstView = tempTexture.createView( {
  46660. baseMipLevel: 0,
  46661. mipLevelCount: 1,
  46662. dimension: GPUTextureViewDimension.TwoD,
  46663. baseArrayLayer: 0
  46664. } );
  46665. const commandEncoder = this.device.createCommandEncoder( {} );
  46666. const pass = ( pipeline, sourceView, destinationView ) => {
  46667. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  46668. const bindGroup = this.device.createBindGroup( {
  46669. layout: bindGroupLayout,
  46670. entries: [ {
  46671. binding: 0,
  46672. resource: this.flipYSampler
  46673. }, {
  46674. binding: 1,
  46675. resource: sourceView
  46676. } ]
  46677. } );
  46678. const passEncoder = commandEncoder.beginRenderPass( {
  46679. colorAttachments: [ {
  46680. view: destinationView,
  46681. loadOp: GPULoadOp.Clear,
  46682. storeOp: GPUStoreOp.Store,
  46683. clearValue: [ 0, 0, 0, 0 ]
  46684. } ]
  46685. } );
  46686. passEncoder.setPipeline( pipeline );
  46687. passEncoder.setBindGroup( 0, bindGroup );
  46688. passEncoder.draw( 4, 1, 0, 0 );
  46689. passEncoder.end();
  46690. };
  46691. pass( transferPipeline, srcView, dstView );
  46692. pass( flipYPipeline, dstView, srcView );
  46693. this.device.queue.submit( [ commandEncoder.finish() ] );
  46694. tempTexture.destroy();
  46695. }
  46696. /**
  46697. * Generates mipmaps for the given GPU texture.
  46698. *
  46699. * @param {GPUTexture} textureGPU - The GPU texture object.
  46700. * @param {Object} textureGPUDescriptor - The texture descriptor.
  46701. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  46702. */
  46703. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  46704. const textureData = this.get( textureGPU );
  46705. if ( textureData.useCount === undefined ) {
  46706. textureData.useCount = 0;
  46707. textureData.layers = [];
  46708. }
  46709. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  46710. const commandEncoder = this.device.createCommandEncoder( {} );
  46711. this._mipmapRunBundles( commandEncoder, passes );
  46712. this.device.queue.submit( [ commandEncoder.finish() ] );
  46713. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  46714. textureData.useCount ++;
  46715. }
  46716. /**
  46717. * Since multiple copy render passes are required to generate mipmaps, the passes
  46718. * are managed as render bundles to improve performance.
  46719. *
  46720. * @param {GPUTexture} textureGPU - The GPU texture object.
  46721. * @param {Object} textureGPUDescriptor - The texture descriptor.
  46722. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  46723. * @return {Array<Object>} An array of render bundles.
  46724. */
  46725. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  46726. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  46727. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  46728. let srcView = textureGPU.createView( {
  46729. baseMipLevel: 0,
  46730. mipLevelCount: 1,
  46731. dimension: GPUTextureViewDimension.TwoD,
  46732. baseArrayLayer
  46733. } );
  46734. const passes = [];
  46735. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  46736. const bindGroup = this.device.createBindGroup( {
  46737. layout: bindGroupLayout,
  46738. entries: [ {
  46739. binding: 0,
  46740. resource: this.mipmapSampler
  46741. }, {
  46742. binding: 1,
  46743. resource: srcView
  46744. } ]
  46745. } );
  46746. const dstView = textureGPU.createView( {
  46747. baseMipLevel: i,
  46748. mipLevelCount: 1,
  46749. dimension: GPUTextureViewDimension.TwoD,
  46750. baseArrayLayer
  46751. } );
  46752. const passDescriptor = {
  46753. colorAttachments: [ {
  46754. view: dstView,
  46755. loadOp: GPULoadOp.Clear,
  46756. storeOp: GPUStoreOp.Store,
  46757. clearValue: [ 0, 0, 0, 0 ]
  46758. } ]
  46759. };
  46760. const passEncoder = this.device.createRenderBundleEncoder( {
  46761. colorFormats: [ textureGPUDescriptor.format ]
  46762. } );
  46763. passEncoder.setPipeline( pipeline );
  46764. passEncoder.setBindGroup( 0, bindGroup );
  46765. passEncoder.draw( 4, 1, 0, 0 );
  46766. passes.push( {
  46767. renderBundles: [ passEncoder.finish() ],
  46768. passDescriptor
  46769. } );
  46770. srcView = dstView;
  46771. }
  46772. return passes;
  46773. }
  46774. /**
  46775. * Executes the render bundles.
  46776. *
  46777. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  46778. * @param {Array<Object>} passes - An array of render bundles.
  46779. */
  46780. _mipmapRunBundles( commandEncoder, passes ) {
  46781. const levels = passes.length;
  46782. for ( let i = 0; i < levels; i ++ ) {
  46783. const pass = passes[ i ];
  46784. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  46785. passEncoder.executeBundles( pass.renderBundles );
  46786. passEncoder.end();
  46787. }
  46788. }
  46789. }
  46790. const _compareToWebGPU = {
  46791. [ NeverCompare ]: 'never',
  46792. [ LessCompare ]: 'less',
  46793. [ EqualCompare ]: 'equal',
  46794. [ LessEqualCompare ]: 'less-equal',
  46795. [ GreaterCompare ]: 'greater',
  46796. [ GreaterEqualCompare ]: 'greater-equal',
  46797. [ AlwaysCompare ]: 'always',
  46798. [ NotEqualCompare ]: 'not-equal'
  46799. };
  46800. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  46801. /**
  46802. * A WebGPU backend utility module for managing textures.
  46803. *
  46804. * @private
  46805. */
  46806. class WebGPUTextureUtils {
  46807. /**
  46808. * Constructs a new utility object.
  46809. *
  46810. * @param {WebGPUBackend} backend - The WebGPU backend.
  46811. */
  46812. constructor( backend ) {
  46813. /**
  46814. * A reference to the WebGPU backend.
  46815. *
  46816. * @type {WebGPUBackend}
  46817. */
  46818. this.backend = backend;
  46819. /**
  46820. * A reference to the pass utils.
  46821. *
  46822. * @type {?WebGPUTexturePassUtils}
  46823. * @default null
  46824. */
  46825. this._passUtils = null;
  46826. /**
  46827. * A dictionary for managing default textures. The key
  46828. * is the texture format, the value the texture object.
  46829. *
  46830. * @type {Object<string,Texture>}
  46831. */
  46832. this.defaultTexture = {};
  46833. /**
  46834. * A dictionary for managing default cube textures. The key
  46835. * is the texture format, the value the texture object.
  46836. *
  46837. * @type {Object<string,CubeTexture>}
  46838. */
  46839. this.defaultCubeTexture = {};
  46840. /**
  46841. * A default video frame.
  46842. *
  46843. * @type {?VideoFrame}
  46844. * @default null
  46845. */
  46846. this.defaultVideoFrame = null;
  46847. /**
  46848. * Represents the color attachment of the default framebuffer.
  46849. *
  46850. * @type {?GPUTexture}
  46851. * @default null
  46852. */
  46853. this.colorBuffer = null;
  46854. /**
  46855. * Represents the depth attachment of the default framebuffer.
  46856. *
  46857. * @type {DepthTexture}
  46858. */
  46859. this.depthTexture = new DepthTexture();
  46860. this.depthTexture.name = 'depthBuffer';
  46861. }
  46862. /**
  46863. * Creates a GPU sampler for the given texture.
  46864. *
  46865. * @param {Texture} texture - The texture to create the sampler for.
  46866. */
  46867. createSampler( texture ) {
  46868. const backend = this.backend;
  46869. const device = backend.device;
  46870. const textureGPU = backend.get( texture );
  46871. const samplerDescriptorGPU = {
  46872. addressModeU: this._convertAddressMode( texture.wrapS ),
  46873. addressModeV: this._convertAddressMode( texture.wrapT ),
  46874. addressModeW: this._convertAddressMode( texture.wrapR ),
  46875. magFilter: this._convertFilterMode( texture.magFilter ),
  46876. minFilter: this._convertFilterMode( texture.minFilter ),
  46877. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  46878. maxAnisotropy: 1
  46879. };
  46880. // anisotropy can only be used when all filter modes are set to linear.
  46881. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  46882. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  46883. }
  46884. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  46885. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  46886. }
  46887. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  46888. }
  46889. /**
  46890. * Creates a default texture for the given texture that can be used
  46891. * as a placeholder until the actual texture is ready for usage.
  46892. *
  46893. * @param {Texture} texture - The texture to create a default texture for.
  46894. */
  46895. createDefaultTexture( texture ) {
  46896. let textureGPU;
  46897. const format = getFormat( texture );
  46898. if ( texture.isCubeTexture ) {
  46899. textureGPU = this._getDefaultCubeTextureGPU( format );
  46900. } else {
  46901. textureGPU = this._getDefaultTextureGPU( format );
  46902. }
  46903. this.backend.get( texture ).texture = textureGPU;
  46904. }
  46905. /**
  46906. * Defines a texture on the GPU for the given texture object.
  46907. *
  46908. * @param {Texture} texture - The texture.
  46909. * @param {Object} [options={}] - Optional configuration parameter.
  46910. */
  46911. createTexture( texture, options = {} ) {
  46912. const backend = this.backend;
  46913. const textureData = backend.get( texture );
  46914. if ( textureData.initialized ) {
  46915. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  46916. }
  46917. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  46918. if ( options.levels === undefined ) options.levels = 1;
  46919. if ( options.depth === undefined ) options.depth = 1;
  46920. const { width, height, depth, levels } = options;
  46921. if ( texture.isFramebufferTexture ) {
  46922. if ( options.renderTarget ) {
  46923. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  46924. } else {
  46925. options.format = this.backend.utils.getPreferredCanvasFormat();
  46926. }
  46927. }
  46928. const dimension = this._getDimension( texture );
  46929. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  46930. textureData.format = format;
  46931. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  46932. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  46933. if ( texture.isStorageTexture === true ) {
  46934. usage |= GPUTextureUsage.STORAGE_BINDING;
  46935. }
  46936. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  46937. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  46938. }
  46939. const textureDescriptorGPU = {
  46940. label: texture.name,
  46941. size: {
  46942. width: width,
  46943. height: height,
  46944. depthOrArrayLayers: depth,
  46945. },
  46946. mipLevelCount: levels,
  46947. sampleCount: primarySamples,
  46948. dimension: dimension,
  46949. format: format,
  46950. usage: usage
  46951. };
  46952. // texture creation
  46953. if ( format === undefined ) {
  46954. console.warn( 'WebGPURenderer: Texture format not supported.' );
  46955. this.createDefaultTexture( texture );
  46956. return;
  46957. }
  46958. if ( texture.isCubeTexture ) {
  46959. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  46960. }
  46961. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  46962. if ( isMSAA ) {
  46963. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  46964. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  46965. msaaTextureDescriptorGPU.sampleCount = samples;
  46966. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  46967. }
  46968. textureData.initialized = true;
  46969. textureData.textureDescriptorGPU = textureDescriptorGPU;
  46970. }
  46971. /**
  46972. * Destroys the GPU data for the given texture object.
  46973. *
  46974. * @param {Texture} texture - The texture.
  46975. */
  46976. destroyTexture( texture ) {
  46977. const backend = this.backend;
  46978. const textureData = backend.get( texture );
  46979. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  46980. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  46981. backend.delete( texture );
  46982. }
  46983. /**
  46984. * Destroys the GPU sampler for the given texture.
  46985. *
  46986. * @param {Texture} texture - The texture to destroy the sampler for.
  46987. */
  46988. destroySampler( texture ) {
  46989. const backend = this.backend;
  46990. const textureData = backend.get( texture );
  46991. delete textureData.sampler;
  46992. }
  46993. /**
  46994. * Generates mipmaps for the given texture.
  46995. *
  46996. * @param {Texture} texture - The texture.
  46997. */
  46998. generateMipmaps( texture ) {
  46999. const textureData = this.backend.get( texture );
  47000. if ( texture.isCubeTexture ) {
  47001. for ( let i = 0; i < 6; i ++ ) {
  47002. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  47003. }
  47004. } else {
  47005. const depth = texture.image.depth || 1;
  47006. for ( let i = 0; i < depth; i ++ ) {
  47007. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  47008. }
  47009. }
  47010. }
  47011. /**
  47012. * Returns the color buffer representing the color
  47013. * attachment of the default framebuffer.
  47014. *
  47015. * @return {GPUTexture} The color buffer.
  47016. */
  47017. getColorBuffer() {
  47018. if ( this.colorBuffer ) this.colorBuffer.destroy();
  47019. const backend = this.backend;
  47020. const { width, height } = backend.getDrawingBufferSize();
  47021. this.colorBuffer = backend.device.createTexture( {
  47022. label: 'colorBuffer',
  47023. size: {
  47024. width: width,
  47025. height: height,
  47026. depthOrArrayLayers: 1
  47027. },
  47028. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  47029. format: backend.utils.getPreferredCanvasFormat(),
  47030. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  47031. } );
  47032. return this.colorBuffer;
  47033. }
  47034. /**
  47035. * Returns the depth buffer representing the depth
  47036. * attachment of the default framebuffer.
  47037. *
  47038. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  47039. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  47040. * @return {GPUTexture} The depth buffer.
  47041. */
  47042. getDepthBuffer( depth = true, stencil = false ) {
  47043. const backend = this.backend;
  47044. const { width, height } = backend.getDrawingBufferSize();
  47045. const depthTexture = this.depthTexture;
  47046. const depthTextureGPU = backend.get( depthTexture ).texture;
  47047. let format, type;
  47048. if ( stencil ) {
  47049. format = DepthStencilFormat;
  47050. type = UnsignedInt248Type;
  47051. } else if ( depth ) {
  47052. format = DepthFormat;
  47053. type = UnsignedIntType;
  47054. }
  47055. if ( depthTextureGPU !== undefined ) {
  47056. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  47057. return depthTextureGPU;
  47058. }
  47059. this.destroyTexture( depthTexture );
  47060. }
  47061. depthTexture.name = 'depthBuffer';
  47062. depthTexture.format = format;
  47063. depthTexture.type = type;
  47064. depthTexture.image.width = width;
  47065. depthTexture.image.height = height;
  47066. this.createTexture( depthTexture, { width, height } );
  47067. return backend.get( depthTexture ).texture;
  47068. }
  47069. /**
  47070. * Uploads the updated texture data to the GPU.
  47071. *
  47072. * @param {Texture} texture - The texture.
  47073. * @param {Object} [options={}] - Optional configuration parameter.
  47074. */
  47075. updateTexture( texture, options ) {
  47076. const textureData = this.backend.get( texture );
  47077. const { textureDescriptorGPU } = textureData;
  47078. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  47079. return;
  47080. // transfer texture data
  47081. if ( texture.isDataTexture ) {
  47082. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  47083. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  47084. for ( let i = 0; i < options.image.depth; i ++ ) {
  47085. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  47086. }
  47087. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  47088. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  47089. } else if ( texture.isCubeTexture ) {
  47090. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY, texture.premultiplyAlpha );
  47091. } else {
  47092. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  47093. }
  47094. //
  47095. textureData.version = texture.version;
  47096. if ( texture.onUpdate ) texture.onUpdate( texture );
  47097. }
  47098. /**
  47099. * Returns texture data as a typed array.
  47100. *
  47101. * @async
  47102. * @param {Texture} texture - The texture to copy.
  47103. * @param {number} x - The x coordinate of the copy origin.
  47104. * @param {number} y - The y coordinate of the copy origin.
  47105. * @param {number} width - The width of the copy.
  47106. * @param {number} height - The height of the copy.
  47107. * @param {number} faceIndex - The face index.
  47108. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47109. */
  47110. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47111. const device = this.backend.device;
  47112. const textureData = this.backend.get( texture );
  47113. const textureGPU = textureData.texture;
  47114. const format = textureData.textureDescriptorGPU.format;
  47115. const bytesPerTexel = this._getBytesPerTexel( format );
  47116. let bytesPerRow = width * bytesPerTexel;
  47117. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  47118. const readBuffer = device.createBuffer(
  47119. {
  47120. size: width * height * bytesPerTexel,
  47121. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47122. }
  47123. );
  47124. const encoder = device.createCommandEncoder();
  47125. encoder.copyTextureToBuffer(
  47126. {
  47127. texture: textureGPU,
  47128. origin: { x, y, z: faceIndex },
  47129. },
  47130. {
  47131. buffer: readBuffer,
  47132. bytesPerRow: bytesPerRow
  47133. },
  47134. {
  47135. width: width,
  47136. height: height
  47137. }
  47138. );
  47139. const typedArrayType = this._getTypedArrayType( format );
  47140. device.queue.submit( [ encoder.finish() ] );
  47141. await readBuffer.mapAsync( GPUMapMode.READ );
  47142. const buffer = readBuffer.getMappedRange();
  47143. return new typedArrayType( buffer );
  47144. }
  47145. /**
  47146. * Returns the default GPU texture for the given format.
  47147. *
  47148. * @private
  47149. * @param {string} format - The GPU format.
  47150. * @return {GPUTexture} The GPU texture.
  47151. */
  47152. _getDefaultTextureGPU( format ) {
  47153. let defaultTexture = this.defaultTexture[ format ];
  47154. if ( defaultTexture === undefined ) {
  47155. const texture = new Texture();
  47156. texture.minFilter = NearestFilter;
  47157. texture.magFilter = NearestFilter;
  47158. this.createTexture( texture, { width: 1, height: 1, format } );
  47159. this.defaultTexture[ format ] = defaultTexture = texture;
  47160. }
  47161. return this.backend.get( defaultTexture ).texture;
  47162. }
  47163. /**
  47164. * Returns the default GPU cube texture for the given format.
  47165. *
  47166. * @private
  47167. * @param {string} format - The GPU format.
  47168. * @return {GPUTexture} The GPU texture.
  47169. */
  47170. _getDefaultCubeTextureGPU( format ) {
  47171. let defaultCubeTexture = this.defaultTexture[ format ];
  47172. if ( defaultCubeTexture === undefined ) {
  47173. const texture = new CubeTexture();
  47174. texture.minFilter = NearestFilter;
  47175. texture.magFilter = NearestFilter;
  47176. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  47177. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  47178. }
  47179. return this.backend.get( defaultCubeTexture ).texture;
  47180. }
  47181. /**
  47182. * Uploads cube texture image data to the GPU memory.
  47183. *
  47184. * @private
  47185. * @param {Array} images - The cube image data.
  47186. * @param {GPUTexture} textureGPU - The GPU texture.
  47187. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47188. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  47189. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  47190. */
  47191. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY, premultiplyAlpha ) {
  47192. for ( let i = 0; i < 6; i ++ ) {
  47193. const image = images[ i ];
  47194. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  47195. if ( image.isDataTexture ) {
  47196. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  47197. } else {
  47198. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY, premultiplyAlpha );
  47199. }
  47200. }
  47201. }
  47202. /**
  47203. * Uploads texture image data to the GPU memory.
  47204. *
  47205. * @private
  47206. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  47207. * @param {GPUTexture} textureGPU - The GPU texture.
  47208. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47209. * @param {number} originDepth - The origin depth.
  47210. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  47211. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  47212. */
  47213. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha ) {
  47214. const device = this.backend.device;
  47215. device.queue.copyExternalImageToTexture(
  47216. {
  47217. source: image,
  47218. flipY: flipY
  47219. }, {
  47220. texture: textureGPU,
  47221. mipLevel: 0,
  47222. origin: { x: 0, y: 0, z: originDepth },
  47223. premultipliedAlpha: premultiplyAlpha
  47224. }, {
  47225. width: textureDescriptorGPU.size.width,
  47226. height: textureDescriptorGPU.size.height,
  47227. depthOrArrayLayers: 1
  47228. }
  47229. );
  47230. }
  47231. /**
  47232. * Returns the pass utils singleton.
  47233. *
  47234. * @private
  47235. * @return {WebGPUTexturePassUtils} The utils instance.
  47236. */
  47237. _getPassUtils() {
  47238. let passUtils = this._passUtils;
  47239. if ( passUtils === null ) {
  47240. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  47241. }
  47242. return passUtils;
  47243. }
  47244. /**
  47245. * Generates mipmaps for the given GPU texture.
  47246. *
  47247. * @private
  47248. * @param {GPUTexture} textureGPU - The GPU texture object.
  47249. * @param {Object} textureDescriptorGPU - The texture descriptor.
  47250. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  47251. */
  47252. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  47253. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  47254. }
  47255. /**
  47256. * Flip the contents of the given GPU texture along its vertical axis.
  47257. *
  47258. * @private
  47259. * @param {GPUTexture} textureGPU - The GPU texture object.
  47260. * @param {Object} textureDescriptorGPU - The texture descriptor.
  47261. * @param {number} [originDepth=0] - The origin depth.
  47262. */
  47263. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  47264. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  47265. }
  47266. /**
  47267. * Uploads texture buffer data to the GPU memory.
  47268. *
  47269. * @private
  47270. * @param {Object} image - An object defining the image buffer data.
  47271. * @param {GPUTexture} textureGPU - The GPU texture.
  47272. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47273. * @param {number} originDepth - The origin depth.
  47274. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  47275. * @param {number} [depth=0] - TODO.
  47276. */
  47277. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  47278. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  47279. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  47280. const device = this.backend.device;
  47281. const data = image.data;
  47282. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  47283. const bytesPerRow = image.width * bytesPerTexel;
  47284. device.queue.writeTexture(
  47285. {
  47286. texture: textureGPU,
  47287. mipLevel: 0,
  47288. origin: { x: 0, y: 0, z: originDepth }
  47289. },
  47290. data,
  47291. {
  47292. offset: image.width * image.height * bytesPerTexel * depth,
  47293. bytesPerRow
  47294. },
  47295. {
  47296. width: image.width,
  47297. height: image.height,
  47298. depthOrArrayLayers: 1
  47299. } );
  47300. if ( flipY === true ) {
  47301. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  47302. }
  47303. }
  47304. /**
  47305. * Uploads compressed texture data to the GPU memory.
  47306. *
  47307. * @private
  47308. * @param {Array<Object>} mipmaps - An array with mipmap data.
  47309. * @param {GPUTexture} textureGPU - The GPU texture.
  47310. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47311. */
  47312. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  47313. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  47314. const device = this.backend.device;
  47315. const blockData = this._getBlockData( textureDescriptorGPU.format );
  47316. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  47317. for ( let i = 0; i < mipmaps.length; i ++ ) {
  47318. const mipmap = mipmaps[ i ];
  47319. const width = mipmap.width;
  47320. const height = mipmap.height;
  47321. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  47322. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  47323. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  47324. for ( let j = 0; j < depth; j ++ ) {
  47325. device.queue.writeTexture(
  47326. {
  47327. texture: textureGPU,
  47328. mipLevel: i,
  47329. origin: { x: 0, y: 0, z: j }
  47330. },
  47331. mipmap.data,
  47332. {
  47333. offset: j * bytesPerImage,
  47334. bytesPerRow,
  47335. rowsPerImage: Math.ceil( height / blockData.height )
  47336. },
  47337. {
  47338. width: Math.ceil( width / blockData.width ) * blockData.width,
  47339. height: Math.ceil( height / blockData.height ) * blockData.height,
  47340. depthOrArrayLayers: 1
  47341. }
  47342. );
  47343. }
  47344. }
  47345. }
  47346. /**
  47347. * This method is only relevant for compressed texture formats. It returns a block
  47348. * data descriptor for the given GPU compressed texture format.
  47349. *
  47350. * @private
  47351. * @param {string} format - The GPU compressed texture format.
  47352. * @return {Object} The block data descriptor.
  47353. */
  47354. _getBlockData( format ) {
  47355. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  47356. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  47357. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  47358. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  47359. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  47360. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  47361. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  47362. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  47363. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  47364. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  47365. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  47366. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  47367. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  47368. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  47369. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  47370. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  47371. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  47372. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  47373. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  47374. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  47375. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  47376. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  47377. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  47378. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  47379. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  47380. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  47381. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  47382. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  47383. }
  47384. /**
  47385. * Converts the three.js uv wrapping constants to GPU address mode constants.
  47386. *
  47387. * @private
  47388. * @param {number} value - The three.js constant defining a uv wrapping mode.
  47389. * @return {string} The GPU address mode.
  47390. */
  47391. _convertAddressMode( value ) {
  47392. let addressMode = GPUAddressMode.ClampToEdge;
  47393. if ( value === RepeatWrapping ) {
  47394. addressMode = GPUAddressMode.Repeat;
  47395. } else if ( value === MirroredRepeatWrapping ) {
  47396. addressMode = GPUAddressMode.MirrorRepeat;
  47397. }
  47398. return addressMode;
  47399. }
  47400. /**
  47401. * Converts the three.js filter constants to GPU filter constants.
  47402. *
  47403. * @private
  47404. * @param {number} value - The three.js constant defining a filter mode.
  47405. * @return {string} The GPU filter mode.
  47406. */
  47407. _convertFilterMode( value ) {
  47408. let filterMode = GPUFilterMode.Linear;
  47409. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  47410. filterMode = GPUFilterMode.Nearest;
  47411. }
  47412. return filterMode;
  47413. }
  47414. /**
  47415. * Returns the bytes-per-texel value for the given GPU texture format.
  47416. *
  47417. * @private
  47418. * @param {string} format - The GPU texture format.
  47419. * @return {number} The bytes-per-texel.
  47420. */
  47421. _getBytesPerTexel( format ) {
  47422. // 8-bit formats
  47423. if ( format === GPUTextureFormat.R8Unorm ||
  47424. format === GPUTextureFormat.R8Snorm ||
  47425. format === GPUTextureFormat.R8Uint ||
  47426. format === GPUTextureFormat.R8Sint ) return 1;
  47427. // 16-bit formats
  47428. if ( format === GPUTextureFormat.R16Uint ||
  47429. format === GPUTextureFormat.R16Sint ||
  47430. format === GPUTextureFormat.R16Float ||
  47431. format === GPUTextureFormat.RG8Unorm ||
  47432. format === GPUTextureFormat.RG8Snorm ||
  47433. format === GPUTextureFormat.RG8Uint ||
  47434. format === GPUTextureFormat.RG8Sint ) return 2;
  47435. // 32-bit formats
  47436. if ( format === GPUTextureFormat.R32Uint ||
  47437. format === GPUTextureFormat.R32Sint ||
  47438. format === GPUTextureFormat.R32Float ||
  47439. format === GPUTextureFormat.RG16Uint ||
  47440. format === GPUTextureFormat.RG16Sint ||
  47441. format === GPUTextureFormat.RG16Float ||
  47442. format === GPUTextureFormat.RGBA8Unorm ||
  47443. format === GPUTextureFormat.RGBA8UnormSRGB ||
  47444. format === GPUTextureFormat.RGBA8Snorm ||
  47445. format === GPUTextureFormat.RGBA8Uint ||
  47446. format === GPUTextureFormat.RGBA8Sint ||
  47447. format === GPUTextureFormat.BGRA8Unorm ||
  47448. format === GPUTextureFormat.BGRA8UnormSRGB ||
  47449. // Packed 32-bit formats
  47450. format === GPUTextureFormat.RGB9E5UFloat ||
  47451. format === GPUTextureFormat.RGB10A2Unorm ||
  47452. format === GPUTextureFormat.RG11B10UFloat ||
  47453. format === GPUTextureFormat.Depth32Float ||
  47454. format === GPUTextureFormat.Depth24Plus ||
  47455. format === GPUTextureFormat.Depth24PlusStencil8 ||
  47456. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  47457. // 64-bit formats
  47458. if ( format === GPUTextureFormat.RG32Uint ||
  47459. format === GPUTextureFormat.RG32Sint ||
  47460. format === GPUTextureFormat.RG32Float ||
  47461. format === GPUTextureFormat.RGBA16Uint ||
  47462. format === GPUTextureFormat.RGBA16Sint ||
  47463. format === GPUTextureFormat.RGBA16Float ) return 8;
  47464. // 128-bit formats
  47465. if ( format === GPUTextureFormat.RGBA32Uint ||
  47466. format === GPUTextureFormat.RGBA32Sint ||
  47467. format === GPUTextureFormat.RGBA32Float ) return 16;
  47468. }
  47469. /**
  47470. * Returns the corresponding typed array type for the given GPU texture format.
  47471. *
  47472. * @private
  47473. * @param {string} format - The GPU texture format.
  47474. * @return {TypedArray.constructor} The typed array type.
  47475. */
  47476. _getTypedArrayType( format ) {
  47477. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  47478. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  47479. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  47480. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  47481. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  47482. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  47483. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  47484. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  47485. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  47486. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  47487. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  47488. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  47489. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  47490. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  47491. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  47492. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  47493. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  47494. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  47495. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  47496. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  47497. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  47498. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  47499. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  47500. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  47501. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  47502. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  47503. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  47504. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  47505. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  47506. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  47507. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  47508. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  47509. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  47510. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  47511. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  47512. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  47513. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  47514. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  47515. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  47516. }
  47517. /**
  47518. * Returns the GPU dimensions for the given texture.
  47519. *
  47520. * @private
  47521. * @param {Texture} texture - The texture.
  47522. * @return {string} The GPU dimension.
  47523. */
  47524. _getDimension( texture ) {
  47525. let dimension;
  47526. if ( texture.is3DTexture || texture.isData3DTexture ) {
  47527. dimension = GPUTextureDimension.ThreeD;
  47528. } else {
  47529. dimension = GPUTextureDimension.TwoD;
  47530. }
  47531. return dimension;
  47532. }
  47533. }
  47534. /**
  47535. * Returns the GPU format for the given texture.
  47536. *
  47537. * @param {Texture} texture - The texture.
  47538. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  47539. * It is not necessary to apply the device for most formats.
  47540. * @return {string} The GPU format.
  47541. */
  47542. function getFormat( texture, device = null ) {
  47543. const format = texture.format;
  47544. const type = texture.type;
  47545. const colorSpace = texture.colorSpace;
  47546. const transfer = ColorManagement.getTransfer( colorSpace );
  47547. let formatGPU;
  47548. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  47549. switch ( format ) {
  47550. case RGBA_S3TC_DXT1_Format:
  47551. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  47552. break;
  47553. case RGBA_S3TC_DXT3_Format:
  47554. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  47555. break;
  47556. case RGBA_S3TC_DXT5_Format:
  47557. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  47558. break;
  47559. case RGB_ETC2_Format:
  47560. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  47561. break;
  47562. case RGBA_ETC2_EAC_Format:
  47563. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  47564. break;
  47565. case RGBA_ASTC_4x4_Format:
  47566. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  47567. break;
  47568. case RGBA_ASTC_5x4_Format:
  47569. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  47570. break;
  47571. case RGBA_ASTC_5x5_Format:
  47572. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  47573. break;
  47574. case RGBA_ASTC_6x5_Format:
  47575. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  47576. break;
  47577. case RGBA_ASTC_6x6_Format:
  47578. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  47579. break;
  47580. case RGBA_ASTC_8x5_Format:
  47581. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  47582. break;
  47583. case RGBA_ASTC_8x6_Format:
  47584. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  47585. break;
  47586. case RGBA_ASTC_8x8_Format:
  47587. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  47588. break;
  47589. case RGBA_ASTC_10x5_Format:
  47590. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  47591. break;
  47592. case RGBA_ASTC_10x6_Format:
  47593. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  47594. break;
  47595. case RGBA_ASTC_10x8_Format:
  47596. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  47597. break;
  47598. case RGBA_ASTC_10x10_Format:
  47599. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  47600. break;
  47601. case RGBA_ASTC_12x10_Format:
  47602. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  47603. break;
  47604. case RGBA_ASTC_12x12_Format:
  47605. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  47606. break;
  47607. case RGBAFormat:
  47608. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  47609. break;
  47610. default:
  47611. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  47612. }
  47613. } else {
  47614. switch ( format ) {
  47615. case RGBAFormat:
  47616. switch ( type ) {
  47617. case ByteType:
  47618. formatGPU = GPUTextureFormat.RGBA8Snorm;
  47619. break;
  47620. case ShortType:
  47621. formatGPU = GPUTextureFormat.RGBA16Sint;
  47622. break;
  47623. case UnsignedShortType:
  47624. formatGPU = GPUTextureFormat.RGBA16Uint;
  47625. break;
  47626. case UnsignedIntType:
  47627. formatGPU = GPUTextureFormat.RGBA32Uint;
  47628. break;
  47629. case IntType:
  47630. formatGPU = GPUTextureFormat.RGBA32Sint;
  47631. break;
  47632. case UnsignedByteType:
  47633. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  47634. break;
  47635. case HalfFloatType:
  47636. formatGPU = GPUTextureFormat.RGBA16Float;
  47637. break;
  47638. case FloatType:
  47639. formatGPU = GPUTextureFormat.RGBA32Float;
  47640. break;
  47641. default:
  47642. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  47643. }
  47644. break;
  47645. case RGBFormat:
  47646. switch ( type ) {
  47647. case UnsignedInt5999Type:
  47648. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  47649. break;
  47650. default:
  47651. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  47652. }
  47653. break;
  47654. case RedFormat:
  47655. switch ( type ) {
  47656. case ByteType:
  47657. formatGPU = GPUTextureFormat.R8Snorm;
  47658. break;
  47659. case ShortType:
  47660. formatGPU = GPUTextureFormat.R16Sint;
  47661. break;
  47662. case UnsignedShortType:
  47663. formatGPU = GPUTextureFormat.R16Uint;
  47664. break;
  47665. case UnsignedIntType:
  47666. formatGPU = GPUTextureFormat.R32Uint;
  47667. break;
  47668. case IntType:
  47669. formatGPU = GPUTextureFormat.R32Sint;
  47670. break;
  47671. case UnsignedByteType:
  47672. formatGPU = GPUTextureFormat.R8Unorm;
  47673. break;
  47674. case HalfFloatType:
  47675. formatGPU = GPUTextureFormat.R16Float;
  47676. break;
  47677. case FloatType:
  47678. formatGPU = GPUTextureFormat.R32Float;
  47679. break;
  47680. default:
  47681. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  47682. }
  47683. break;
  47684. case RGFormat:
  47685. switch ( type ) {
  47686. case ByteType:
  47687. formatGPU = GPUTextureFormat.RG8Snorm;
  47688. break;
  47689. case ShortType:
  47690. formatGPU = GPUTextureFormat.RG16Sint;
  47691. break;
  47692. case UnsignedShortType:
  47693. formatGPU = GPUTextureFormat.RG16Uint;
  47694. break;
  47695. case UnsignedIntType:
  47696. formatGPU = GPUTextureFormat.RG32Uint;
  47697. break;
  47698. case IntType:
  47699. formatGPU = GPUTextureFormat.RG32Sint;
  47700. break;
  47701. case UnsignedByteType:
  47702. formatGPU = GPUTextureFormat.RG8Unorm;
  47703. break;
  47704. case HalfFloatType:
  47705. formatGPU = GPUTextureFormat.RG16Float;
  47706. break;
  47707. case FloatType:
  47708. formatGPU = GPUTextureFormat.RG32Float;
  47709. break;
  47710. default:
  47711. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  47712. }
  47713. break;
  47714. case DepthFormat:
  47715. switch ( type ) {
  47716. case UnsignedShortType:
  47717. formatGPU = GPUTextureFormat.Depth16Unorm;
  47718. break;
  47719. case UnsignedIntType:
  47720. formatGPU = GPUTextureFormat.Depth24Plus;
  47721. break;
  47722. case FloatType:
  47723. formatGPU = GPUTextureFormat.Depth32Float;
  47724. break;
  47725. default:
  47726. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  47727. }
  47728. break;
  47729. case DepthStencilFormat:
  47730. switch ( type ) {
  47731. case UnsignedInt248Type:
  47732. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  47733. break;
  47734. case FloatType:
  47735. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  47736. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  47737. }
  47738. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  47739. break;
  47740. default:
  47741. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  47742. }
  47743. break;
  47744. case RedIntegerFormat:
  47745. switch ( type ) {
  47746. case IntType:
  47747. formatGPU = GPUTextureFormat.R32Sint;
  47748. break;
  47749. case UnsignedIntType:
  47750. formatGPU = GPUTextureFormat.R32Uint;
  47751. break;
  47752. default:
  47753. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  47754. }
  47755. break;
  47756. case RGIntegerFormat:
  47757. switch ( type ) {
  47758. case IntType:
  47759. formatGPU = GPUTextureFormat.RG32Sint;
  47760. break;
  47761. case UnsignedIntType:
  47762. formatGPU = GPUTextureFormat.RG32Uint;
  47763. break;
  47764. default:
  47765. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  47766. }
  47767. break;
  47768. case RGBAIntegerFormat:
  47769. switch ( type ) {
  47770. case IntType:
  47771. formatGPU = GPUTextureFormat.RGBA32Sint;
  47772. break;
  47773. case UnsignedIntType:
  47774. formatGPU = GPUTextureFormat.RGBA32Uint;
  47775. break;
  47776. default:
  47777. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  47778. }
  47779. break;
  47780. default:
  47781. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  47782. }
  47783. }
  47784. return formatGPU;
  47785. }
  47786. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  47787. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  47788. const wgslTypeLib$1 = {
  47789. 'f32': 'float',
  47790. 'i32': 'int',
  47791. 'u32': 'uint',
  47792. 'bool': 'bool',
  47793. 'vec2<f32>': 'vec2',
  47794. 'vec2<i32>': 'ivec2',
  47795. 'vec2<u32>': 'uvec2',
  47796. 'vec2<bool>': 'bvec2',
  47797. 'vec2f': 'vec2',
  47798. 'vec2i': 'ivec2',
  47799. 'vec2u': 'uvec2',
  47800. 'vec2b': 'bvec2',
  47801. 'vec3<f32>': 'vec3',
  47802. 'vec3<i32>': 'ivec3',
  47803. 'vec3<u32>': 'uvec3',
  47804. 'vec3<bool>': 'bvec3',
  47805. 'vec3f': 'vec3',
  47806. 'vec3i': 'ivec3',
  47807. 'vec3u': 'uvec3',
  47808. 'vec3b': 'bvec3',
  47809. 'vec4<f32>': 'vec4',
  47810. 'vec4<i32>': 'ivec4',
  47811. 'vec4<u32>': 'uvec4',
  47812. 'vec4<bool>': 'bvec4',
  47813. 'vec4f': 'vec4',
  47814. 'vec4i': 'ivec4',
  47815. 'vec4u': 'uvec4',
  47816. 'vec4b': 'bvec4',
  47817. 'mat2x2<f32>': 'mat2',
  47818. 'mat2x2f': 'mat2',
  47819. 'mat3x3<f32>': 'mat3',
  47820. 'mat3x3f': 'mat3',
  47821. 'mat4x4<f32>': 'mat4',
  47822. 'mat4x4f': 'mat4',
  47823. 'sampler': 'sampler',
  47824. 'texture_1d': 'texture',
  47825. 'texture_2d': 'texture',
  47826. 'texture_2d_array': 'texture',
  47827. 'texture_multisampled_2d': 'cubeTexture',
  47828. 'texture_depth_2d': 'depthTexture',
  47829. 'texture_depth_2d_array': 'depthTexture',
  47830. 'texture_depth_multisampled_2d': 'depthTexture',
  47831. 'texture_depth_cube': 'depthTexture',
  47832. 'texture_depth_cube_array': 'depthTexture',
  47833. 'texture_3d': 'texture3D',
  47834. 'texture_cube': 'cubeTexture',
  47835. 'texture_cube_array': 'cubeTexture',
  47836. 'texture_storage_1d': 'storageTexture',
  47837. 'texture_storage_2d': 'storageTexture',
  47838. 'texture_storage_2d_array': 'storageTexture',
  47839. 'texture_storage_3d': 'storageTexture'
  47840. };
  47841. const parse = ( source ) => {
  47842. source = source.trim();
  47843. const declaration = source.match( declarationRegexp );
  47844. if ( declaration !== null && declaration.length === 4 ) {
  47845. const inputsCode = declaration[ 2 ];
  47846. const propsMatches = [];
  47847. let match = null;
  47848. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  47849. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  47850. }
  47851. // Process matches to correctly pair names and types
  47852. const inputs = [];
  47853. for ( let i = 0; i < propsMatches.length; i ++ ) {
  47854. const { name, type } = propsMatches[ i ];
  47855. let resolvedType = type;
  47856. if ( resolvedType.startsWith( 'ptr' ) ) {
  47857. resolvedType = 'pointer';
  47858. } else {
  47859. if ( resolvedType.startsWith( 'texture' ) ) {
  47860. resolvedType = type.split( '<' )[ 0 ];
  47861. }
  47862. resolvedType = wgslTypeLib$1[ resolvedType ];
  47863. }
  47864. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  47865. }
  47866. const blockCode = source.substring( declaration[ 0 ].length );
  47867. const outputType = declaration[ 3 ] || 'void';
  47868. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  47869. const type = wgslTypeLib$1[ outputType ] || outputType;
  47870. return {
  47871. type,
  47872. inputs,
  47873. name,
  47874. inputsCode,
  47875. blockCode,
  47876. outputType
  47877. };
  47878. } else {
  47879. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  47880. }
  47881. };
  47882. /**
  47883. * This class represents a WSL node function.
  47884. *
  47885. * @augments NodeFunction
  47886. */
  47887. class WGSLNodeFunction extends NodeFunction {
  47888. /**
  47889. * Constructs a new WGSL node function.
  47890. *
  47891. * @param {string} source - The WGSL source.
  47892. */
  47893. constructor( source ) {
  47894. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  47895. super( type, inputs, name );
  47896. this.inputsCode = inputsCode;
  47897. this.blockCode = blockCode;
  47898. this.outputType = outputType;
  47899. }
  47900. /**
  47901. * This method returns the WGSL code of the node function.
  47902. *
  47903. * @param {string} [name=this.name] - The function's name.
  47904. * @return {string} The shader code.
  47905. */
  47906. getCode( name = this.name ) {
  47907. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  47908. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  47909. }
  47910. }
  47911. /**
  47912. * A WGSL node parser.
  47913. *
  47914. * @augments NodeParser
  47915. */
  47916. class WGSLNodeParser extends NodeParser {
  47917. /**
  47918. * The method parses the given WGSL code an returns a node function.
  47919. *
  47920. * @param {string} source - The WGSL code.
  47921. * @return {WGSLNodeFunction} A node function.
  47922. */
  47923. parseFunction( source ) {
  47924. return new WGSLNodeFunction( source );
  47925. }
  47926. }
  47927. // GPUShaderStage is not defined in browsers not supporting WebGPU
  47928. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  47929. const accessNames = {
  47930. [ NodeAccess.READ_ONLY ]: 'read',
  47931. [ NodeAccess.WRITE_ONLY ]: 'write',
  47932. [ NodeAccess.READ_WRITE ]: 'read_write'
  47933. };
  47934. const wrapNames = {
  47935. [ RepeatWrapping ]: 'repeat',
  47936. [ ClampToEdgeWrapping ]: 'clamp',
  47937. [ MirroredRepeatWrapping ]: 'mirror'
  47938. };
  47939. const gpuShaderStageLib = {
  47940. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  47941. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  47942. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  47943. };
  47944. const supports = {
  47945. instance: true,
  47946. swizzleAssign: false,
  47947. storageBuffer: true
  47948. };
  47949. const wgslFnOpLib = {
  47950. '^^': 'tsl_xor'
  47951. };
  47952. const wgslTypeLib = {
  47953. float: 'f32',
  47954. int: 'i32',
  47955. uint: 'u32',
  47956. bool: 'bool',
  47957. color: 'vec3<f32>',
  47958. vec2: 'vec2<f32>',
  47959. ivec2: 'vec2<i32>',
  47960. uvec2: 'vec2<u32>',
  47961. bvec2: 'vec2<bool>',
  47962. vec3: 'vec3<f32>',
  47963. ivec3: 'vec3<i32>',
  47964. uvec3: 'vec3<u32>',
  47965. bvec3: 'vec3<bool>',
  47966. vec4: 'vec4<f32>',
  47967. ivec4: 'vec4<i32>',
  47968. uvec4: 'vec4<u32>',
  47969. bvec4: 'vec4<bool>',
  47970. mat2: 'mat2x2<f32>',
  47971. mat3: 'mat3x3<f32>',
  47972. mat4: 'mat4x4<f32>'
  47973. };
  47974. const wgslCodeCache = {};
  47975. const wgslPolyfill = {
  47976. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  47977. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  47978. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  47979. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  47980. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  47981. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  47982. 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 ); }' ),
  47983. 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 ); }' ),
  47984. 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 ); }' ),
  47985. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  47986. 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 ); }' ),
  47987. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  47988. biquadraticTexture: new CodeNode( /* wgsl */`
  47989. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  47990. let res = vec2f( iRes );
  47991. let uvScaled = coord * res;
  47992. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  47993. // https://www.shadertoy.com/view/WtyXRy
  47994. let uv = uvWrapping - 0.5;
  47995. let iuv = floor( uv );
  47996. let f = fract( uv );
  47997. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  47998. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  47999. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  48000. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  48001. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  48002. }
  48003. ` )
  48004. };
  48005. const wgslMethods = {
  48006. dFdx: 'dpdx',
  48007. dFdy: '- dpdy',
  48008. mod_float: 'tsl_mod_float',
  48009. mod_vec2: 'tsl_mod_vec2',
  48010. mod_vec3: 'tsl_mod_vec3',
  48011. mod_vec4: 'tsl_mod_vec4',
  48012. equals_bool: 'tsl_equals_bool',
  48013. equals_bvec2: 'tsl_equals_bvec2',
  48014. equals_bvec3: 'tsl_equals_bvec3',
  48015. equals_bvec4: 'tsl_equals_bvec4',
  48016. inversesqrt: 'inverseSqrt',
  48017. bitcast: 'bitcast<f32>'
  48018. };
  48019. // WebGPU issue: does not support pow() with negative base on Windows
  48020. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  48021. 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 ); }' );
  48022. 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 ] );
  48023. 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 ] );
  48024. 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 ] );
  48025. wgslMethods.pow_float = 'tsl_pow_float';
  48026. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  48027. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  48028. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  48029. }
  48030. //
  48031. let diagnostics = '';
  48032. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  48033. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  48034. }
  48035. /**
  48036. * A node builder targeting WGSL.
  48037. *
  48038. * This module generates WGSL shader code from node materials and also
  48039. * generates the respective bindings and vertex buffer definitions. These
  48040. * data are later used by the renderer to create render and compute pipelines
  48041. * for render objects.
  48042. *
  48043. * @augments NodeBuilder
  48044. */
  48045. class WGSLNodeBuilder extends NodeBuilder {
  48046. /**
  48047. * Constructs a new WGSL node builder renderer.
  48048. *
  48049. * @param {Object3D} object - The 3D object.
  48050. * @param {Renderer} renderer - The renderer.
  48051. */
  48052. constructor( object, renderer ) {
  48053. super( object, renderer, new WGSLNodeParser() );
  48054. /**
  48055. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  48056. * another dictionary which manages UBOs per group ('render','frame','object').
  48057. *
  48058. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  48059. */
  48060. this.uniformGroups = {};
  48061. /**
  48062. * A dictionary that holds for each shader stage a Map of builtins.
  48063. *
  48064. * @type {Object<string,Map<string,Object>>}
  48065. */
  48066. this.builtins = {};
  48067. /**
  48068. * A dictionary that holds for each shader stage a Set of directives.
  48069. *
  48070. * @type {Object<string,Set<string>>}
  48071. */
  48072. this.directives = {};
  48073. /**
  48074. * A map for managing scope arrays. Only relevant for when using
  48075. * {@link WorkgroupInfoNode} in context of compute shaders.
  48076. *
  48077. * @type {Map<string,Object>}
  48078. */
  48079. this.scopedArrays = new Map();
  48080. }
  48081. /**
  48082. * Generates the WGSL snippet for sampled textures.
  48083. *
  48084. * @private
  48085. * @param {Texture} texture - The texture.
  48086. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48087. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48088. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48089. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48090. * @return {string} The WGSL snippet.
  48091. */
  48092. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48093. if ( shaderStage === 'fragment' ) {
  48094. if ( depthSnippet ) {
  48095. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  48096. } else {
  48097. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  48098. }
  48099. } else {
  48100. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  48101. }
  48102. }
  48103. /**
  48104. * Generates the WGSL snippet when sampling textures with explicit mip level.
  48105. *
  48106. * @private
  48107. * @param {Texture} texture - The texture.
  48108. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48109. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48110. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48111. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48112. * @return {string} The WGSL snippet.
  48113. */
  48114. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  48115. if ( this.isUnfilterable( texture ) === false ) {
  48116. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  48117. } else if ( this.isFilteredTexture( texture ) ) {
  48118. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  48119. } else {
  48120. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  48121. }
  48122. }
  48123. /**
  48124. * Generates a wrap function used in context of textures.
  48125. *
  48126. * @param {Texture} texture - The texture to generate the function for.
  48127. * @return {string} The name of the generated function.
  48128. */
  48129. generateWrapFunction( texture ) {
  48130. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  48131. let nodeCode = wgslCodeCache[ functionName ];
  48132. if ( nodeCode === undefined ) {
  48133. const includes = [];
  48134. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  48135. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  48136. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  48137. const addWrapSnippet = ( wrap, axis ) => {
  48138. if ( wrap === RepeatWrapping ) {
  48139. includes.push( wgslPolyfill.repeatWrapping_float );
  48140. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  48141. } else if ( wrap === ClampToEdgeWrapping ) {
  48142. includes.push( wgslPolyfill.clampWrapping_float );
  48143. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  48144. } else if ( wrap === MirroredRepeatWrapping ) {
  48145. includes.push( wgslPolyfill.mirrorWrapping_float );
  48146. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  48147. } else {
  48148. code += `\t\tcoord.${ axis }`;
  48149. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  48150. }
  48151. };
  48152. addWrapSnippet( texture.wrapS, 'x' );
  48153. code += ',\n';
  48154. addWrapSnippet( texture.wrapT, 'y' );
  48155. if ( texture.isData3DTexture ) {
  48156. code += ',\n';
  48157. addWrapSnippet( texture.wrapR, 'z' );
  48158. }
  48159. code += '\n\t);\n\n}\n';
  48160. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  48161. }
  48162. nodeCode.build( this );
  48163. return functionName;
  48164. }
  48165. /**
  48166. * Generates the array declaration string.
  48167. *
  48168. * @param {string} type - The type.
  48169. * @param {?number} [count] - The count.
  48170. * @return {string} The generated value as a shader string.
  48171. */
  48172. generateArrayDeclaration( type, count ) {
  48173. return `array< ${ this.getType( type ) }, ${ count } >`;
  48174. }
  48175. /**
  48176. * Generates a WGSL variable that holds the texture dimension of the given texture.
  48177. * It also returns information about the number of layers (elements) of an arrayed
  48178. * texture as well as the cube face count of cube textures.
  48179. *
  48180. * @param {Texture} texture - The texture to generate the function for.
  48181. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  48182. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48183. * @return {string} The name of the dimension variable.
  48184. */
  48185. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  48186. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  48187. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  48188. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  48189. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  48190. let textureDimensionsParams;
  48191. let dimensionType;
  48192. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  48193. const isMultisampled = primarySamples > 1;
  48194. if ( texture.isData3DTexture ) {
  48195. dimensionType = 'vec3<u32>';
  48196. } else {
  48197. // Regular 2D textures, depth textures, etc.
  48198. dimensionType = 'vec2<u32>';
  48199. }
  48200. // Build parameters string based on texture type and multisampling
  48201. if ( isMultisampled || texture.isStorageTexture ) {
  48202. textureDimensionsParams = textureProperty;
  48203. } else {
  48204. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  48205. }
  48206. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  48207. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  48208. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  48209. textureData.arrayLayerCount = new VarNode(
  48210. new ExpressionNode(
  48211. `textureNumLayers(${textureProperty})`,
  48212. 'u32'
  48213. )
  48214. );
  48215. }
  48216. // For cube textures, we know it's always 6 faces
  48217. if ( texture.isTextureCube ) {
  48218. textureData.cubeFaceCount = new VarNode(
  48219. new ExpressionNode( '6u', 'u32' )
  48220. );
  48221. }
  48222. }
  48223. return textureDimensionNode.build( this );
  48224. }
  48225. /**
  48226. * Generates the WGSL snippet for a manual filtered texture.
  48227. *
  48228. * @param {Texture} texture - The texture.
  48229. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48230. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48231. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48232. * @return {string} The WGSL snippet.
  48233. */
  48234. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  48235. this._include( 'biquadraticTexture' );
  48236. const wrapFunction = this.generateWrapFunction( texture );
  48237. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  48238. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  48239. }
  48240. /**
  48241. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  48242. * Since it's a lookup, no sampling or filtering is applied.
  48243. *
  48244. * @param {Texture} texture - The texture.
  48245. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48246. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48247. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48248. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48249. * @return {string} The WGSL snippet.
  48250. */
  48251. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  48252. const wrapFunction = this.generateWrapFunction( texture );
  48253. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  48254. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  48255. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  48256. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  48257. }
  48258. /**
  48259. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  48260. *
  48261. * @param {Texture} texture - The texture.
  48262. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48263. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48264. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48265. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48266. * @return {string} The WGSL snippet.
  48267. */
  48268. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  48269. let snippet;
  48270. if ( depthSnippet ) {
  48271. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  48272. } else {
  48273. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  48274. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  48275. snippet += '.x';
  48276. }
  48277. }
  48278. return snippet;
  48279. }
  48280. /**
  48281. * Generates the WGSL snippet that writes a single texel to a texture.
  48282. *
  48283. * @param {Texture} texture - The texture.
  48284. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48285. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48286. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48287. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  48288. * @return {string} The WGSL snippet.
  48289. */
  48290. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  48291. let snippet;
  48292. if ( depthSnippet ) {
  48293. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  48294. } else {
  48295. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  48296. }
  48297. return snippet;
  48298. }
  48299. /**
  48300. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  48301. *
  48302. * @param {Texture} texture - The texture.
  48303. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  48304. */
  48305. isSampleCompare( texture ) {
  48306. return texture.isDepthTexture === true && texture.compareFunction !== null;
  48307. }
  48308. /**
  48309. * Returns `true` if the given texture is unfilterable.
  48310. *
  48311. * @param {Texture} texture - The texture.
  48312. * @return {boolean} Whether the given texture is unfilterable or not.
  48313. */
  48314. isUnfilterable( texture ) {
  48315. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  48316. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  48317. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  48318. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  48319. }
  48320. /**
  48321. * Generates the WGSL snippet for sampling/loading the given texture.
  48322. *
  48323. * @param {Texture} texture - The texture.
  48324. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48325. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48326. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48327. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48328. * @return {string} The WGSL snippet.
  48329. */
  48330. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48331. let snippet = null;
  48332. if ( this.isUnfilterable( texture ) ) {
  48333. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  48334. } else {
  48335. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  48336. }
  48337. return snippet;
  48338. }
  48339. /**
  48340. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  48341. *
  48342. * @param {Texture} texture - The texture.
  48343. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48344. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48345. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  48346. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48347. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48348. * @return {string} The WGSL snippet.
  48349. */
  48350. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48351. if ( shaderStage === 'fragment' ) {
  48352. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  48353. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  48354. } else {
  48355. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  48356. }
  48357. }
  48358. /**
  48359. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  48360. * against a reference value.
  48361. *
  48362. * @param {Texture} texture - The texture.
  48363. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48364. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48365. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  48366. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48367. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48368. * @return {string} The WGSL snippet.
  48369. */
  48370. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48371. if ( shaderStage === 'fragment' ) {
  48372. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  48373. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  48374. }
  48375. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  48376. } else {
  48377. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  48378. }
  48379. }
  48380. /**
  48381. * Generates the WGSL snippet when sampling textures with explicit mip level.
  48382. *
  48383. * @param {Texture} texture - The texture.
  48384. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48385. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48386. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48387. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48388. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48389. * @return {string} The WGSL snippet.
  48390. */
  48391. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  48392. if ( this.isUnfilterable( texture ) === false ) {
  48393. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  48394. } else if ( this.isFilteredTexture( texture ) ) {
  48395. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  48396. } else {
  48397. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  48398. }
  48399. }
  48400. /**
  48401. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  48402. *
  48403. * @param {Texture} texture - The texture.
  48404. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48405. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48406. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  48407. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48408. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48409. * @return {string} The WGSL snippet.
  48410. */
  48411. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48412. if ( shaderStage === 'fragment' ) {
  48413. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  48414. } else {
  48415. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  48416. }
  48417. }
  48418. /**
  48419. * Returns a WGSL snippet that represents the property name of the given node.
  48420. *
  48421. * @param {Node} node - The node.
  48422. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48423. * @return {string} The property name.
  48424. */
  48425. getPropertyName( node, shaderStage = this.shaderStage ) {
  48426. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  48427. if ( shaderStage === 'vertex' ) {
  48428. return `varyings.${ node.name }`;
  48429. }
  48430. } else if ( node.isNodeUniform === true ) {
  48431. const name = node.name;
  48432. const type = node.type;
  48433. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  48434. return name;
  48435. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  48436. if ( this.isCustomStruct( node ) ) {
  48437. return name;
  48438. }
  48439. return name + '.value';
  48440. } else {
  48441. return node.groupNode.name + '.' + name;
  48442. }
  48443. }
  48444. return super.getPropertyName( node );
  48445. }
  48446. /**
  48447. * Returns the output struct name.
  48448. *
  48449. * @return {string} The name of the output struct.
  48450. */
  48451. getOutputStructName() {
  48452. return 'output';
  48453. }
  48454. /**
  48455. * Returns the native shader operator name for a given generic name.
  48456. *
  48457. * @param {string} op - The operator name to resolve.
  48458. * @return {?string} The resolved operator name.
  48459. */
  48460. getFunctionOperator( op ) {
  48461. const fnOp = wgslFnOpLib[ op ];
  48462. if ( fnOp !== undefined ) {
  48463. this._include( fnOp );
  48464. return fnOp;
  48465. }
  48466. return null;
  48467. }
  48468. /**
  48469. * Returns the node access for the given node and shader stage.
  48470. *
  48471. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  48472. * @param {string} shaderStage - The shader stage.
  48473. * @return {string} The node access.
  48474. */
  48475. getNodeAccess( node, shaderStage ) {
  48476. if ( shaderStage !== 'compute' ) {
  48477. if ( node.isAtomic === true ) {
  48478. console.warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  48479. return NodeAccess.READ_WRITE;
  48480. }
  48481. return NodeAccess.READ_ONLY;
  48482. }
  48483. return node.access;
  48484. }
  48485. /**
  48486. * Returns A WGSL snippet representing the storage access.
  48487. *
  48488. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  48489. * @param {string} shaderStage - The shader stage.
  48490. * @return {string} The WGSL snippet representing the storage access.
  48491. */
  48492. getStorageAccess( node, shaderStage ) {
  48493. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  48494. }
  48495. /**
  48496. * This method is one of the more important ones since it's responsible
  48497. * for generating a matching binding instance for the given uniform node.
  48498. *
  48499. * These bindings are later used in the renderer to create bind groups
  48500. * and layouts.
  48501. *
  48502. * @param {UniformNode} node - The uniform node.
  48503. * @param {string} type - The node data type.
  48504. * @param {string} shaderStage - The shader stage.
  48505. * @param {?string} [name=null] - An optional uniform name.
  48506. * @return {NodeUniform} The node uniform object.
  48507. */
  48508. getUniformFromNode( node, type, shaderStage, name = null ) {
  48509. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  48510. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  48511. if ( nodeData.uniformGPU === undefined ) {
  48512. let uniformGPU;
  48513. const group = node.groupNode;
  48514. const groupName = group.name;
  48515. const bindings = this.getBindGroupArray( groupName, shaderStage );
  48516. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  48517. let texture = null;
  48518. const access = this.getNodeAccess( node, shaderStage );
  48519. if ( type === 'texture' || type === 'storageTexture' ) {
  48520. if ( node.value.is3DTexture === true ) {
  48521. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  48522. } else {
  48523. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  48524. }
  48525. } else if ( type === 'cubeTexture' ) {
  48526. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  48527. } else if ( type === 'texture3D' ) {
  48528. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  48529. }
  48530. texture.store = node.isStorageTextureNode === true;
  48531. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  48532. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  48533. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  48534. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  48535. bindings.push( sampler, texture );
  48536. uniformGPU = [ sampler, texture ];
  48537. } else {
  48538. bindings.push( texture );
  48539. uniformGPU = [ texture ];
  48540. }
  48541. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  48542. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  48543. const buffer = new bufferClass( node, group );
  48544. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  48545. bindings.push( buffer );
  48546. uniformGPU = buffer;
  48547. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  48548. } else {
  48549. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  48550. let uniformsGroup = uniformsStage[ groupName ];
  48551. if ( uniformsGroup === undefined ) {
  48552. uniformsGroup = new NodeUniformsGroup( groupName, group );
  48553. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  48554. uniformsStage[ groupName ] = uniformsGroup;
  48555. bindings.push( uniformsGroup );
  48556. }
  48557. uniformGPU = this.getNodeUniform( uniformNode, type );
  48558. uniformsGroup.addUniform( uniformGPU );
  48559. }
  48560. nodeData.uniformGPU = uniformGPU;
  48561. }
  48562. return uniformNode;
  48563. }
  48564. /**
  48565. * This method should be used whenever builtins are required in nodes.
  48566. * The internal builtins data structure will make sure builtins are
  48567. * defined in the WGSL source.
  48568. *
  48569. * @param {string} name - The builtin name.
  48570. * @param {string} property - The property name.
  48571. * @param {string} type - The node data type.
  48572. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48573. * @return {string} The property name.
  48574. */
  48575. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  48576. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  48577. if ( map.has( name ) === false ) {
  48578. map.set( name, {
  48579. name,
  48580. property,
  48581. type
  48582. } );
  48583. }
  48584. return property;
  48585. }
  48586. /**
  48587. * Returns `true` if the given builtin is defined in the given shader stage.
  48588. *
  48589. * @param {string} name - The builtin name.
  48590. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48591. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  48592. */
  48593. hasBuiltin( name, shaderStage = this.shaderStage ) {
  48594. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  48595. }
  48596. /**
  48597. * Returns the vertex index builtin.
  48598. *
  48599. * @return {string} The vertex index.
  48600. */
  48601. getVertexIndex() {
  48602. if ( this.shaderStage === 'vertex' ) {
  48603. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  48604. }
  48605. return 'vertexIndex';
  48606. }
  48607. /**
  48608. * Builds the given shader node.
  48609. *
  48610. * @param {ShaderNodeInternal} shaderNode - The shader node.
  48611. * @return {string} The WGSL function code.
  48612. */
  48613. buildFunctionCode( shaderNode ) {
  48614. const layout = shaderNode.layout;
  48615. const flowData = this.flowShaderNode( shaderNode );
  48616. const parameters = [];
  48617. for ( const input of layout.inputs ) {
  48618. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  48619. }
  48620. //
  48621. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  48622. ${ flowData.vars }
  48623. ${ flowData.code }
  48624. `;
  48625. if ( flowData.result ) {
  48626. code += `\treturn ${ flowData.result };\n`;
  48627. }
  48628. code += '\n}\n';
  48629. //
  48630. return code;
  48631. }
  48632. /**
  48633. * Returns the instance index builtin.
  48634. *
  48635. * @return {string} The instance index.
  48636. */
  48637. getInstanceIndex() {
  48638. if ( this.shaderStage === 'vertex' ) {
  48639. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  48640. }
  48641. return 'instanceIndex';
  48642. }
  48643. /**
  48644. * Returns the invocation local index builtin.
  48645. *
  48646. * @return {string} The invocation local index.
  48647. */
  48648. getInvocationLocalIndex() {
  48649. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  48650. }
  48651. /**
  48652. * Returns the subgroup size builtin.
  48653. *
  48654. * @return {string} The subgroup size.
  48655. */
  48656. getSubgroupSize() {
  48657. this.enableSubGroups();
  48658. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  48659. }
  48660. /**
  48661. * Returns the invocation subgroup index builtin.
  48662. *
  48663. * @return {string} The invocation subgroup index.
  48664. */
  48665. getInvocationSubgroupIndex() {
  48666. this.enableSubGroups();
  48667. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  48668. }
  48669. /**
  48670. * Returns the subgroup index builtin.
  48671. *
  48672. * @return {string} The subgroup index.
  48673. */
  48674. getSubgroupIndex() {
  48675. this.enableSubGroups();
  48676. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  48677. }
  48678. /**
  48679. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  48680. *
  48681. * @return {null} Null.
  48682. */
  48683. getDrawIndex() {
  48684. return null;
  48685. }
  48686. /**
  48687. * Returns the front facing builtin.
  48688. *
  48689. * @return {string} The front facing builtin.
  48690. */
  48691. getFrontFacing() {
  48692. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  48693. }
  48694. /**
  48695. * Returns the frag coord builtin.
  48696. *
  48697. * @return {string} The frag coord builtin.
  48698. */
  48699. getFragCoord() {
  48700. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  48701. }
  48702. /**
  48703. * Returns the frag depth builtin.
  48704. *
  48705. * @return {string} The frag depth builtin.
  48706. */
  48707. getFragDepth() {
  48708. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  48709. }
  48710. /**
  48711. * Returns the clip distances builtin.
  48712. *
  48713. * @return {string} The clip distances builtin.
  48714. */
  48715. getClipDistance() {
  48716. return 'varyings.hw_clip_distances';
  48717. }
  48718. /**
  48719. * Whether to flip texture data along its vertical axis or not.
  48720. *
  48721. * @return {boolean} Returns always `false` in context of WGSL.
  48722. */
  48723. isFlipY() {
  48724. return false;
  48725. }
  48726. /**
  48727. * Enables the given directive for the given shader stage.
  48728. *
  48729. * @param {string} name - The directive name.
  48730. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  48731. */
  48732. enableDirective( name, shaderStage = this.shaderStage ) {
  48733. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  48734. stage.add( name );
  48735. }
  48736. /**
  48737. * Returns the directives of the given shader stage as a WGSL string.
  48738. *
  48739. * @param {string} shaderStage - The shader stage.
  48740. * @return {string} A WGSL snippet that enables the directives of the given stage.
  48741. */
  48742. getDirectives( shaderStage ) {
  48743. const snippets = [];
  48744. const directives = this.directives[ shaderStage ];
  48745. if ( directives !== undefined ) {
  48746. for ( const directive of directives ) {
  48747. snippets.push( `enable ${directive};` );
  48748. }
  48749. }
  48750. return snippets.join( '\n' );
  48751. }
  48752. /**
  48753. * Enables the 'subgroups' directive.
  48754. */
  48755. enableSubGroups() {
  48756. this.enableDirective( 'subgroups' );
  48757. }
  48758. /**
  48759. * Enables the 'subgroups-f16' directive.
  48760. */
  48761. enableSubgroupsF16() {
  48762. this.enableDirective( 'subgroups-f16' );
  48763. }
  48764. /**
  48765. * Enables the 'clip_distances' directive.
  48766. */
  48767. enableClipDistances() {
  48768. this.enableDirective( 'clip_distances' );
  48769. }
  48770. /**
  48771. * Enables the 'f16' directive.
  48772. */
  48773. enableShaderF16() {
  48774. this.enableDirective( 'f16' );
  48775. }
  48776. /**
  48777. * Enables the 'dual_source_blending' directive.
  48778. */
  48779. enableDualSourceBlending() {
  48780. this.enableDirective( 'dual_source_blending' );
  48781. }
  48782. /**
  48783. * Enables hardware clipping.
  48784. *
  48785. * @param {string} planeCount - The clipping plane count.
  48786. */
  48787. enableHardwareClipping( planeCount ) {
  48788. this.enableClipDistances();
  48789. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  48790. }
  48791. /**
  48792. * Returns the builtins of the given shader stage as a WGSL string.
  48793. *
  48794. * @param {string} shaderStage - The shader stage.
  48795. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  48796. */
  48797. getBuiltins( shaderStage ) {
  48798. const snippets = [];
  48799. const builtins = this.builtins[ shaderStage ];
  48800. if ( builtins !== undefined ) {
  48801. for ( const { name, property, type } of builtins.values() ) {
  48802. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  48803. }
  48804. }
  48805. return snippets.join( ',\n\t' );
  48806. }
  48807. /**
  48808. * This method should be used when a new scoped buffer is used in context of
  48809. * compute shaders. It adds the array to the internal data structure which is
  48810. * later used to generate the respective WGSL.
  48811. *
  48812. * @param {string} name - The array name.
  48813. * @param {string} scope - The scope.
  48814. * @param {string} bufferType - The buffer type.
  48815. * @param {string} bufferCount - The buffer count.
  48816. * @return {string} The array name.
  48817. */
  48818. getScopedArray( name, scope, bufferType, bufferCount ) {
  48819. if ( this.scopedArrays.has( name ) === false ) {
  48820. this.scopedArrays.set( name, {
  48821. name,
  48822. scope,
  48823. bufferType,
  48824. bufferCount
  48825. } );
  48826. }
  48827. return name;
  48828. }
  48829. /**
  48830. * Returns the scoped arrays of the given shader stage as a WGSL string.
  48831. *
  48832. * @param {string} shaderStage - The shader stage.
  48833. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  48834. * Returns `undefined` when used in the vertex or fragment stage.
  48835. */
  48836. getScopedArrays( shaderStage ) {
  48837. if ( shaderStage !== 'compute' ) {
  48838. return;
  48839. }
  48840. const snippets = [];
  48841. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  48842. const type = this.getType( bufferType );
  48843. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  48844. }
  48845. return snippets.join( '\n' );
  48846. }
  48847. /**
  48848. * Returns the shader attributes of the given shader stage as a WGSL string.
  48849. *
  48850. * @param {string} shaderStage - The shader stage.
  48851. * @return {string} The WGSL snippet that defines the shader attributes.
  48852. */
  48853. getAttributes( shaderStage ) {
  48854. const snippets = [];
  48855. if ( shaderStage === 'compute' ) {
  48856. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  48857. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  48858. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  48859. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  48860. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  48861. this.enableDirective( 'subgroups', shaderStage );
  48862. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  48863. }
  48864. }
  48865. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  48866. const builtins = this.getBuiltins( 'attribute' );
  48867. if ( builtins ) snippets.push( builtins );
  48868. const attributes = this.getAttributesArray();
  48869. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  48870. const attribute = attributes[ index ];
  48871. const name = attribute.name;
  48872. const type = this.getType( attribute.type );
  48873. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  48874. }
  48875. }
  48876. return snippets.join( ',\n\t' );
  48877. }
  48878. /**
  48879. * Returns the members of the given struct type node as a WGSL string.
  48880. *
  48881. * @param {StructTypeNode} struct - The struct type node.
  48882. * @return {string} The WGSL snippet that defines the struct members.
  48883. */
  48884. getStructMembers( struct ) {
  48885. const snippets = [];
  48886. for ( const member of struct.members ) {
  48887. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  48888. let type = this.getType( member.type );
  48889. if ( member.atomic ) {
  48890. type = 'atomic< ' + type + ' >';
  48891. }
  48892. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  48893. }
  48894. if ( struct.output ) {
  48895. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  48896. }
  48897. return snippets.join( ',\n' );
  48898. }
  48899. /**
  48900. * Returns the structs of the given shader stage as a WGSL string.
  48901. *
  48902. * @param {string} shaderStage - The shader stage.
  48903. * @return {string} The WGSL snippet that defines the structs.
  48904. */
  48905. getStructs( shaderStage ) {
  48906. let result = '';
  48907. const structs = this.structs[ shaderStage ];
  48908. if ( structs.length > 0 ) {
  48909. const snippets = [];
  48910. for ( const struct of structs ) {
  48911. let snippet = `struct ${ struct.name } {\n`;
  48912. snippet += this.getStructMembers( struct );
  48913. snippet += '\n};';
  48914. snippets.push( snippet );
  48915. }
  48916. result = '\n' + snippets.join( '\n\n' ) + '\n';
  48917. }
  48918. return result;
  48919. }
  48920. /**
  48921. * Returns a WGSL string representing a variable.
  48922. *
  48923. * @param {string} type - The variable's type.
  48924. * @param {string} name - The variable's name.
  48925. * @param {?number} [count=null] - The array length.
  48926. * @return {string} The WGSL snippet that defines a variable.
  48927. */
  48928. getVar( type, name, count = null ) {
  48929. let snippet = `var ${ name } : `;
  48930. if ( count !== null ) {
  48931. snippet += this.generateArrayDeclaration( type, count );
  48932. } else {
  48933. snippet += this.getType( type );
  48934. }
  48935. return snippet;
  48936. }
  48937. /**
  48938. * Returns the variables of the given shader stage as a WGSL string.
  48939. *
  48940. * @param {string} shaderStage - The shader stage.
  48941. * @return {string} The WGSL snippet that defines the variables.
  48942. */
  48943. getVars( shaderStage ) {
  48944. const snippets = [];
  48945. const vars = this.vars[ shaderStage ];
  48946. if ( vars !== undefined ) {
  48947. for ( const variable of vars ) {
  48948. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  48949. }
  48950. }
  48951. return `\n${ snippets.join( '\n' ) }\n`;
  48952. }
  48953. /**
  48954. * Returns the varyings of the given shader stage as a WGSL string.
  48955. *
  48956. * @param {string} shaderStage - The shader stage.
  48957. * @return {string} The WGSL snippet that defines the varyings.
  48958. */
  48959. getVaryings( shaderStage ) {
  48960. const snippets = [];
  48961. if ( shaderStage === 'vertex' ) {
  48962. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  48963. }
  48964. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  48965. const varyings = this.varyings;
  48966. const vars = this.vars[ shaderStage ];
  48967. for ( let index = 0; index < varyings.length; index ++ ) {
  48968. const varying = varyings[ index ];
  48969. if ( varying.needsInterpolation ) {
  48970. let attributesSnippet = `@location( ${index} )`;
  48971. if ( varying.interpolationType ) {
  48972. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  48973. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  48974. // Otherwise, optimize interpolation when sensible
  48975. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  48976. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  48977. }
  48978. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  48979. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  48980. vars.push( varying );
  48981. }
  48982. }
  48983. }
  48984. const builtins = this.getBuiltins( shaderStage );
  48985. if ( builtins ) snippets.push( builtins );
  48986. const code = snippets.join( ',\n\t' );
  48987. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  48988. }
  48989. isCustomStruct( nodeUniform ) {
  48990. const attribute = nodeUniform.value;
  48991. const bufferNode = nodeUniform.node;
  48992. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  48993. const isStructArray =
  48994. ( bufferNode.value && bufferNode.value.array ) &&
  48995. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  48996. return isAttributeStructType && ! isStructArray;
  48997. }
  48998. /**
  48999. * Returns the uniforms of the given shader stage as a WGSL string.
  49000. *
  49001. * @param {string} shaderStage - The shader stage.
  49002. * @return {string} The WGSL snippet that defines the uniforms.
  49003. */
  49004. getUniforms( shaderStage ) {
  49005. const uniforms = this.uniforms[ shaderStage ];
  49006. const bindingSnippets = [];
  49007. const bufferSnippets = [];
  49008. const structSnippets = [];
  49009. const uniformGroups = {};
  49010. for ( const uniform of uniforms ) {
  49011. const groupName = uniform.groupNode.name;
  49012. const uniformIndexes = this.bindingsIndexes[ groupName ];
  49013. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  49014. const texture = uniform.node.value;
  49015. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  49016. if ( this.isSampleCompare( texture ) ) {
  49017. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  49018. } else {
  49019. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  49020. }
  49021. }
  49022. let textureType;
  49023. let multisampled = '';
  49024. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  49025. if ( primarySamples > 1 ) {
  49026. multisampled = '_multisampled';
  49027. }
  49028. if ( texture.isCubeTexture === true ) {
  49029. textureType = 'texture_cube<f32>';
  49030. } else if ( texture.isDepthTexture === true ) {
  49031. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  49032. textureType = `texture${ multisampled }_2d<f32>`;
  49033. } else {
  49034. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  49035. }
  49036. } else if ( uniform.node.isStorageTextureNode === true ) {
  49037. const format = getFormat( texture );
  49038. const access = this.getStorageAccess( uniform.node, shaderStage );
  49039. const is3D = uniform.node.value.is3DTexture;
  49040. const isArrayTexture = uniform.node.value.isArrayTexture;
  49041. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  49042. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  49043. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  49044. textureType = 'texture_2d_array<f32>';
  49045. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  49046. textureType = 'texture_3d<f32>';
  49047. } else {
  49048. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  49049. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  49050. }
  49051. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  49052. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  49053. const bufferNode = uniform.node;
  49054. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  49055. const bufferCount = bufferNode.bufferCount;
  49056. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  49057. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  49058. if ( this.isCustomStruct( uniform ) ) {
  49059. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  49060. } else {
  49061. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  49062. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  49063. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  49064. }
  49065. } else {
  49066. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  49067. const groupName = uniform.groupNode.name;
  49068. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  49069. index: uniformIndexes.binding ++,
  49070. id: uniformIndexes.group,
  49071. snippets: []
  49072. } );
  49073. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  49074. }
  49075. }
  49076. for ( const name in uniformGroups ) {
  49077. const group = uniformGroups[ name ];
  49078. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  49079. }
  49080. let code = bindingSnippets.join( '\n' );
  49081. code += bufferSnippets.join( '\n' );
  49082. code += structSnippets.join( '\n' );
  49083. return code;
  49084. }
  49085. /**
  49086. * Controls the code build of the shader stages.
  49087. */
  49088. buildCode() {
  49089. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  49090. this.sortBindingGroups();
  49091. for ( const shaderStage in shadersData ) {
  49092. this.shaderStage = shaderStage;
  49093. const stageData = shadersData[ shaderStage ];
  49094. stageData.uniforms = this.getUniforms( shaderStage );
  49095. stageData.attributes = this.getAttributes( shaderStage );
  49096. stageData.varyings = this.getVaryings( shaderStage );
  49097. stageData.structs = this.getStructs( shaderStage );
  49098. stageData.vars = this.getVars( shaderStage );
  49099. stageData.codes = this.getCodes( shaderStage );
  49100. stageData.directives = this.getDirectives( shaderStage );
  49101. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  49102. //
  49103. let flow = '// code\n\n';
  49104. flow += this.flowCode[ shaderStage ];
  49105. const flowNodes = this.flowNodes[ shaderStage ];
  49106. const mainNode = flowNodes[ flowNodes.length - 1 ];
  49107. const outputNode = mainNode.outputNode;
  49108. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  49109. for ( const node of flowNodes ) {
  49110. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  49111. const slotName = node.name;
  49112. if ( slotName ) {
  49113. if ( flow.length > 0 ) flow += '\n';
  49114. flow += `\t// flow -> ${ slotName }\n`;
  49115. }
  49116. flow += `${ flowSlotData.code }\n\t`;
  49117. if ( node === mainNode && shaderStage !== 'compute' ) {
  49118. flow += '// result\n\n\t';
  49119. if ( shaderStage === 'vertex' ) {
  49120. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  49121. } else if ( shaderStage === 'fragment' ) {
  49122. if ( isOutputStruct ) {
  49123. stageData.returnType = outputNode.getNodeType( this );
  49124. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  49125. flow += `return ${ flowSlotData.result };`;
  49126. } else {
  49127. let structSnippet = '\t@location(0) color: vec4<f32>';
  49128. const builtins = this.getBuiltins( 'output' );
  49129. if ( builtins ) structSnippet += ',\n\t' + builtins;
  49130. stageData.returnType = 'OutputStruct';
  49131. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  49132. stageData.structs += '\nvar<private> output : OutputStruct;';
  49133. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  49134. }
  49135. }
  49136. }
  49137. }
  49138. stageData.flow = flow;
  49139. }
  49140. this.shaderStage = null;
  49141. if ( this.material !== null ) {
  49142. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  49143. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  49144. } else {
  49145. // Early strictly validated in computeNode
  49146. const workgroupSize = this.object.workgroupSize;
  49147. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  49148. }
  49149. }
  49150. /**
  49151. * Returns the native shader method name for a given generic name.
  49152. *
  49153. * @param {string} method - The method name to resolve.
  49154. * @param {?string} [output=null] - An optional output.
  49155. * @return {string} The resolved WGSL method name.
  49156. */
  49157. getMethod( method, output = null ) {
  49158. let wgslMethod;
  49159. if ( output !== null ) {
  49160. wgslMethod = this._getWGSLMethod( method + '_' + output );
  49161. }
  49162. if ( wgslMethod === undefined ) {
  49163. wgslMethod = this._getWGSLMethod( method );
  49164. }
  49165. return wgslMethod || method;
  49166. }
  49167. /**
  49168. * Returns the WGSL type of the given node data type.
  49169. *
  49170. * @param {string} type - The node data type.
  49171. * @return {string} The WGSL type.
  49172. */
  49173. getType( type ) {
  49174. return wgslTypeLib[ type ] || type;
  49175. }
  49176. /**
  49177. * Whether the requested feature is available or not.
  49178. *
  49179. * @param {string} name - The requested feature.
  49180. * @return {boolean} Whether the requested feature is supported or not.
  49181. */
  49182. isAvailable( name ) {
  49183. let result = supports[ name ];
  49184. if ( result === undefined ) {
  49185. if ( name === 'float32Filterable' ) {
  49186. result = this.renderer.hasFeature( 'float32-filterable' );
  49187. } else if ( name === 'clipDistance' ) {
  49188. result = this.renderer.hasFeature( 'clip-distances' );
  49189. }
  49190. supports[ name ] = result;
  49191. }
  49192. return result;
  49193. }
  49194. /**
  49195. * Returns the native shader method name for a given generic name.
  49196. *
  49197. * @private
  49198. * @param {string} method - The method name to resolve.
  49199. * @return {string} The resolved WGSL method name.
  49200. */
  49201. _getWGSLMethod( method ) {
  49202. if ( wgslPolyfill[ method ] !== undefined ) {
  49203. this._include( method );
  49204. }
  49205. return wgslMethods[ method ];
  49206. }
  49207. /**
  49208. * Includes the given method name into the current
  49209. * function node.
  49210. *
  49211. * @private
  49212. * @param {string} name - The method name to include.
  49213. * @return {CodeNode} The respective code node.
  49214. */
  49215. _include( name ) {
  49216. const codeNode = wgslPolyfill[ name ];
  49217. codeNode.build( this );
  49218. if ( this.currentFunctionNode !== null ) {
  49219. this.currentFunctionNode.includes.push( codeNode );
  49220. }
  49221. return codeNode;
  49222. }
  49223. /**
  49224. * Returns a WGSL vertex shader based on the given shader data.
  49225. *
  49226. * @private
  49227. * @param {Object} shaderData - The shader data.
  49228. * @return {string} The vertex shader.
  49229. */
  49230. _getWGSLVertexCode( shaderData ) {
  49231. return `${ this.getSignature() }
  49232. // directives
  49233. ${shaderData.directives}
  49234. // structs
  49235. ${shaderData.structs}
  49236. // uniforms
  49237. ${shaderData.uniforms}
  49238. // varyings
  49239. ${shaderData.varyings}
  49240. var<private> varyings : VaryingsStruct;
  49241. // codes
  49242. ${shaderData.codes}
  49243. @vertex
  49244. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  49245. // vars
  49246. ${shaderData.vars}
  49247. // flow
  49248. ${shaderData.flow}
  49249. return varyings;
  49250. }
  49251. `;
  49252. }
  49253. /**
  49254. * Returns a WGSL fragment shader based on the given shader data.
  49255. *
  49256. * @private
  49257. * @param {Object} shaderData - The shader data.
  49258. * @return {string} The vertex shader.
  49259. */
  49260. _getWGSLFragmentCode( shaderData ) {
  49261. return `${ this.getSignature() }
  49262. // global
  49263. ${ diagnostics }
  49264. // structs
  49265. ${shaderData.structs}
  49266. // uniforms
  49267. ${shaderData.uniforms}
  49268. // codes
  49269. ${shaderData.codes}
  49270. @fragment
  49271. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  49272. // vars
  49273. ${shaderData.vars}
  49274. // flow
  49275. ${shaderData.flow}
  49276. }
  49277. `;
  49278. }
  49279. /**
  49280. * Returns a WGSL compute shader based on the given shader data.
  49281. *
  49282. * @private
  49283. * @param {Object} shaderData - The shader data.
  49284. * @param {string} workgroupSize - The workgroup size.
  49285. * @return {string} The vertex shader.
  49286. */
  49287. _getWGSLComputeCode( shaderData, workgroupSize ) {
  49288. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  49289. return `${ this.getSignature() }
  49290. // directives
  49291. ${ shaderData.directives }
  49292. // system
  49293. var<private> instanceIndex : u32;
  49294. // locals
  49295. ${ shaderData.scopedArrays }
  49296. // structs
  49297. ${ shaderData.structs }
  49298. // uniforms
  49299. ${ shaderData.uniforms }
  49300. // codes
  49301. ${ shaderData.codes }
  49302. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  49303. fn main( ${ shaderData.attributes } ) {
  49304. // system
  49305. instanceIndex = globalId.x
  49306. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  49307. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  49308. // vars
  49309. ${ shaderData.vars }
  49310. // flow
  49311. ${ shaderData.flow }
  49312. }
  49313. `;
  49314. }
  49315. /**
  49316. * Returns a WGSL struct based on the given name and variables.
  49317. *
  49318. * @private
  49319. * @param {string} name - The struct name.
  49320. * @param {string} vars - The struct variables.
  49321. * @return {string} The WGSL snippet representing a struct.
  49322. */
  49323. _getWGSLStruct( name, vars ) {
  49324. return `
  49325. struct ${name} {
  49326. ${vars}
  49327. };`;
  49328. }
  49329. /**
  49330. * Returns a WGSL struct binding.
  49331. *
  49332. * @private
  49333. * @param {string} name - The struct name.
  49334. * @param {string} vars - The struct variables.
  49335. * @param {string} access - The access.
  49336. * @param {number} [binding=0] - The binding index.
  49337. * @param {number} [group=0] - The group index.
  49338. * @return {string} The WGSL snippet representing a struct binding.
  49339. */
  49340. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  49341. const structName = name + 'Struct';
  49342. const structSnippet = this._getWGSLStruct( structName, vars );
  49343. return `${structSnippet}
  49344. @binding( ${ binding } ) @group( ${ group } )
  49345. var<${access}> ${ name } : ${ structName };`;
  49346. }
  49347. }
  49348. /**
  49349. * A WebGPU backend utility module with common helpers.
  49350. *
  49351. * @private
  49352. */
  49353. class WebGPUUtils {
  49354. /**
  49355. * Constructs a new utility object.
  49356. *
  49357. * @param {WebGPUBackend} backend - The WebGPU backend.
  49358. */
  49359. constructor( backend ) {
  49360. /**
  49361. * A reference to the WebGPU backend.
  49362. *
  49363. * @type {WebGPUBackend}
  49364. */
  49365. this.backend = backend;
  49366. }
  49367. /**
  49368. * Returns the depth/stencil GPU format for the given render context.
  49369. *
  49370. * @param {RenderContext} renderContext - The render context.
  49371. * @return {string} The depth/stencil GPU texture format.
  49372. */
  49373. getCurrentDepthStencilFormat( renderContext ) {
  49374. let format;
  49375. if ( renderContext.depthTexture !== null ) {
  49376. format = this.getTextureFormatGPU( renderContext.depthTexture );
  49377. } else if ( renderContext.depth && renderContext.stencil ) {
  49378. format = GPUTextureFormat.Depth24PlusStencil8;
  49379. } else if ( renderContext.depth ) {
  49380. format = GPUTextureFormat.Depth24Plus;
  49381. }
  49382. return format;
  49383. }
  49384. /**
  49385. * Returns the GPU format for the given texture.
  49386. *
  49387. * @param {Texture} texture - The texture.
  49388. * @return {string} The GPU texture format.
  49389. */
  49390. getTextureFormatGPU( texture ) {
  49391. return this.backend.get( texture ).format;
  49392. }
  49393. /**
  49394. * Returns an object that defines the multi-sampling state of the given texture.
  49395. *
  49396. * @param {Texture} texture - The texture.
  49397. * @return {Object} The multi-sampling state.
  49398. */
  49399. getTextureSampleData( texture ) {
  49400. let samples;
  49401. if ( texture.isFramebufferTexture ) {
  49402. samples = 1;
  49403. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  49404. const renderer = this.backend.renderer;
  49405. const renderTarget = renderer.getRenderTarget();
  49406. samples = renderTarget ? renderTarget.samples : renderer.samples;
  49407. } else if ( texture.renderTarget ) {
  49408. samples = texture.renderTarget.samples;
  49409. }
  49410. samples = samples || 1;
  49411. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  49412. const primarySamples = isMSAA ? 1 : samples;
  49413. return { samples, primarySamples, isMSAA };
  49414. }
  49415. /**
  49416. * Returns the default color attachment's GPU format of the current render context.
  49417. *
  49418. * @param {RenderContext} renderContext - The render context.
  49419. * @return {string} The GPU texture format of the default color attachment.
  49420. */
  49421. getCurrentColorFormat( renderContext ) {
  49422. let format;
  49423. if ( renderContext.textures !== null ) {
  49424. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  49425. } else {
  49426. format = this.getPreferredCanvasFormat(); // default context format
  49427. }
  49428. return format;
  49429. }
  49430. /**
  49431. * Returns the output color space of the current render context.
  49432. *
  49433. * @param {RenderContext} renderContext - The render context.
  49434. * @return {string} The output color space.
  49435. */
  49436. getCurrentColorSpace( renderContext ) {
  49437. if ( renderContext.textures !== null ) {
  49438. return renderContext.textures[ 0 ].colorSpace;
  49439. }
  49440. return this.backend.renderer.outputColorSpace;
  49441. }
  49442. /**
  49443. * Returns GPU primitive topology for the given object and material.
  49444. *
  49445. * @param {Object3D} object - The 3D object.
  49446. * @param {Material} material - The material.
  49447. * @return {string} The GPU primitive topology.
  49448. */
  49449. getPrimitiveTopology( object, material ) {
  49450. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  49451. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  49452. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  49453. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  49454. }
  49455. /**
  49456. * Returns a modified sample count from the given sample count value.
  49457. *
  49458. * That is required since WebGPU only supports either 1 or 4.
  49459. *
  49460. * @param {number} sampleCount - The input sample count.
  49461. * @return {number} The (potentially updated) output sample count.
  49462. */
  49463. getSampleCount( sampleCount ) {
  49464. return sampleCount >= 4 ? 4 : 1;
  49465. }
  49466. /**
  49467. * Returns the sample count of the given render context.
  49468. *
  49469. * @param {RenderContext} renderContext - The render context.
  49470. * @return {number} The sample count.
  49471. */
  49472. getSampleCountRenderContext( renderContext ) {
  49473. if ( renderContext.textures !== null ) {
  49474. return this.getSampleCount( renderContext.sampleCount );
  49475. }
  49476. return this.getSampleCount( this.backend.renderer.samples );
  49477. }
  49478. /**
  49479. * Returns the preferred canvas format.
  49480. *
  49481. * There is a separate method for this so it's possible to
  49482. * honor edge cases for specific devices.
  49483. *
  49484. * @return {string} The GPU texture format of the canvas.
  49485. */
  49486. getPreferredCanvasFormat() {
  49487. const outputType = this.backend.parameters.outputType;
  49488. if ( outputType === undefined ) {
  49489. return navigator.gpu.getPreferredCanvasFormat();
  49490. } else if ( outputType === UnsignedByteType ) {
  49491. return GPUTextureFormat.BGRA8Unorm;
  49492. } else if ( outputType === HalfFloatType ) {
  49493. return GPUTextureFormat.RGBA16Float;
  49494. } else {
  49495. throw new Error( 'Unsupported outputType' );
  49496. }
  49497. }
  49498. }
  49499. const typedArraysToVertexFormatPrefix = new Map( [
  49500. [ Int8Array, [ 'sint8', 'snorm8' ]],
  49501. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  49502. [ Int16Array, [ 'sint16', 'snorm16' ]],
  49503. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  49504. [ Int32Array, [ 'sint32', 'snorm32' ]],
  49505. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  49506. [ Float32Array, [ 'float32', ]],
  49507. ] );
  49508. if ( typeof Float16Array !== 'undefined' ) {
  49509. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  49510. }
  49511. const typedAttributeToVertexFormatPrefix = new Map( [
  49512. [ Float16BufferAttribute, [ 'float16', ]],
  49513. ] );
  49514. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  49515. [ Int32Array, 'sint32' ],
  49516. [ Int16Array, 'sint32' ], // patch for INT16
  49517. [ Uint32Array, 'uint32' ],
  49518. [ Uint16Array, 'uint32' ], // patch for UINT16
  49519. [ Float32Array, 'float32' ]
  49520. ] );
  49521. /**
  49522. * A WebGPU backend utility module for managing shader attributes.
  49523. *
  49524. * @private
  49525. */
  49526. class WebGPUAttributeUtils {
  49527. /**
  49528. * Constructs a new utility object.
  49529. *
  49530. * @param {WebGPUBackend} backend - The WebGPU backend.
  49531. */
  49532. constructor( backend ) {
  49533. /**
  49534. * A reference to the WebGPU backend.
  49535. *
  49536. * @type {WebGPUBackend}
  49537. */
  49538. this.backend = backend;
  49539. }
  49540. /**
  49541. * Creates the GPU buffer for the given buffer attribute.
  49542. *
  49543. * @param {BufferAttribute} attribute - The buffer attribute.
  49544. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  49545. */
  49546. createAttribute( attribute, usage ) {
  49547. const bufferAttribute = this._getBufferAttribute( attribute );
  49548. const backend = this.backend;
  49549. const bufferData = backend.get( bufferAttribute );
  49550. let buffer = bufferData.buffer;
  49551. if ( buffer === undefined ) {
  49552. const device = backend.device;
  49553. let array = bufferAttribute.array;
  49554. // patch for INT16 and UINT16
  49555. if ( attribute.normalized === false ) {
  49556. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  49557. array = new Int32Array( array );
  49558. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  49559. array = new Uint32Array( array );
  49560. if ( usage & GPUBufferUsage.INDEX ) {
  49561. for ( let i = 0; i < array.length; i ++ ) {
  49562. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  49563. }
  49564. }
  49565. }
  49566. }
  49567. bufferAttribute.array = array;
  49568. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  49569. array = new array.constructor( bufferAttribute.count * 4 );
  49570. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  49571. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  49572. }
  49573. // Update BufferAttribute
  49574. bufferAttribute.itemSize = 4;
  49575. bufferAttribute.array = array;
  49576. bufferData._force3to4BytesAlignment = true;
  49577. }
  49578. // ensure 4 byte alignment
  49579. const byteLength = array.byteLength;
  49580. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  49581. buffer = device.createBuffer( {
  49582. label: bufferAttribute.name,
  49583. size: size,
  49584. usage: usage,
  49585. mappedAtCreation: true
  49586. } );
  49587. new array.constructor( buffer.getMappedRange() ).set( array );
  49588. buffer.unmap();
  49589. bufferData.buffer = buffer;
  49590. }
  49591. }
  49592. /**
  49593. * Updates the GPU buffer of the given buffer attribute.
  49594. *
  49595. * @param {BufferAttribute} attribute - The buffer attribute.
  49596. */
  49597. updateAttribute( attribute ) {
  49598. const bufferAttribute = this._getBufferAttribute( attribute );
  49599. const backend = this.backend;
  49600. const device = backend.device;
  49601. const bufferData = backend.get( bufferAttribute );
  49602. const buffer = backend.get( bufferAttribute ).buffer;
  49603. let array = bufferAttribute.array;
  49604. // if storage buffer ensure 4 byte alignment
  49605. if ( bufferData._force3to4BytesAlignment === true ) {
  49606. array = new array.constructor( bufferAttribute.count * 4 );
  49607. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  49608. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  49609. }
  49610. bufferAttribute.array = array;
  49611. }
  49612. const isTypedArray = this._isTypedArray( array );
  49613. const updateRanges = bufferAttribute.updateRanges;
  49614. if ( updateRanges.length === 0 ) {
  49615. // Not using update ranges
  49616. device.queue.writeBuffer(
  49617. buffer,
  49618. 0,
  49619. array,
  49620. 0
  49621. );
  49622. } else {
  49623. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  49624. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49625. const range = updateRanges[ i ];
  49626. let dataOffset, size;
  49627. if ( bufferData._force3to4BytesAlignment === true ) {
  49628. const vertexStart = Math.floor( range.start / 3 );
  49629. const vertexCount = Math.ceil( range.count / 3 );
  49630. dataOffset = vertexStart * 4 * byteOffsetFactor;
  49631. size = vertexCount * 4 * byteOffsetFactor;
  49632. } else {
  49633. dataOffset = range.start * byteOffsetFactor;
  49634. size = range.count * byteOffsetFactor;
  49635. }
  49636. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49637. device.queue.writeBuffer(
  49638. buffer,
  49639. bufferOffset,
  49640. array,
  49641. dataOffset,
  49642. size
  49643. );
  49644. }
  49645. bufferAttribute.clearUpdateRanges();
  49646. }
  49647. }
  49648. /**
  49649. * This method creates the vertex buffer layout data which are
  49650. * require when creating a render pipeline for the given render object.
  49651. *
  49652. * @param {RenderObject} renderObject - The render object.
  49653. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  49654. */
  49655. createShaderVertexBuffers( renderObject ) {
  49656. const attributes = renderObject.getAttributes();
  49657. const vertexBuffers = new Map();
  49658. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  49659. const geometryAttribute = attributes[ slot ];
  49660. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  49661. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  49662. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  49663. if ( vertexBufferLayout === undefined ) {
  49664. let arrayStride, stepMode;
  49665. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  49666. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  49667. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  49668. } else {
  49669. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  49670. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  49671. }
  49672. // patch for INT16 and UINT16
  49673. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  49674. arrayStride = 4;
  49675. }
  49676. vertexBufferLayout = {
  49677. arrayStride,
  49678. attributes: [],
  49679. stepMode
  49680. };
  49681. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  49682. }
  49683. const format = this._getVertexFormat( geometryAttribute );
  49684. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  49685. vertexBufferLayout.attributes.push( {
  49686. shaderLocation: slot,
  49687. offset,
  49688. format
  49689. } );
  49690. }
  49691. return Array.from( vertexBuffers.values() );
  49692. }
  49693. /**
  49694. * Destroys the GPU buffer of the given buffer attribute.
  49695. *
  49696. * @param {BufferAttribute} attribute - The buffer attribute.
  49697. */
  49698. destroyAttribute( attribute ) {
  49699. const backend = this.backend;
  49700. const data = backend.get( this._getBufferAttribute( attribute ) );
  49701. data.buffer.destroy();
  49702. backend.delete( attribute );
  49703. }
  49704. /**
  49705. * This method performs a readback operation by moving buffer data from
  49706. * a storage buffer attribute from the GPU to the CPU.
  49707. *
  49708. * @async
  49709. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  49710. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  49711. */
  49712. async getArrayBufferAsync( attribute ) {
  49713. const backend = this.backend;
  49714. const device = backend.device;
  49715. const data = backend.get( this._getBufferAttribute( attribute ) );
  49716. const bufferGPU = data.buffer;
  49717. const size = bufferGPU.size;
  49718. const readBufferGPU = device.createBuffer( {
  49719. label: `${ attribute.name }_readback`,
  49720. size,
  49721. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49722. } );
  49723. const cmdEncoder = device.createCommandEncoder( {
  49724. label: `readback_encoder_${ attribute.name }`
  49725. } );
  49726. cmdEncoder.copyBufferToBuffer(
  49727. bufferGPU,
  49728. 0,
  49729. readBufferGPU,
  49730. 0,
  49731. size
  49732. );
  49733. const gpuCommands = cmdEncoder.finish();
  49734. device.queue.submit( [ gpuCommands ] );
  49735. await readBufferGPU.mapAsync( GPUMapMode.READ );
  49736. const arrayBuffer = readBufferGPU.getMappedRange();
  49737. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  49738. readBufferGPU.unmap();
  49739. return dstBuffer.buffer;
  49740. }
  49741. /**
  49742. * Returns the vertex format of the given buffer attribute.
  49743. *
  49744. * @private
  49745. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  49746. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  49747. */
  49748. _getVertexFormat( geometryAttribute ) {
  49749. const { itemSize, normalized } = geometryAttribute;
  49750. const ArrayType = geometryAttribute.array.constructor;
  49751. const AttributeType = geometryAttribute.constructor;
  49752. let format;
  49753. if ( itemSize === 1 ) {
  49754. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  49755. } else {
  49756. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  49757. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  49758. if ( prefix ) {
  49759. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  49760. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  49761. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  49762. if ( paddedItemSize % 1 ) {
  49763. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  49764. }
  49765. format = `${prefix}x${paddedItemSize}`;
  49766. }
  49767. }
  49768. if ( ! format ) {
  49769. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  49770. }
  49771. return format;
  49772. }
  49773. /**
  49774. * Returns `true` if the given array is a typed array.
  49775. *
  49776. * @private
  49777. * @param {any} array - The array.
  49778. * @return {boolean} Whether the given array is a typed array or not.
  49779. */
  49780. _isTypedArray( array ) {
  49781. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  49782. }
  49783. /**
  49784. * Utility method for handling interleaved buffer attributes correctly.
  49785. * To process them, their `InterleavedBuffer` is returned.
  49786. *
  49787. * @private
  49788. * @param {BufferAttribute} attribute - The attribute.
  49789. * @return {BufferAttribute|InterleavedBuffer}
  49790. */
  49791. _getBufferAttribute( attribute ) {
  49792. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  49793. return attribute;
  49794. }
  49795. }
  49796. /**
  49797. * A WebGPU backend utility module for managing bindings.
  49798. *
  49799. * When reading the documentation it's helpful to keep in mind that
  49800. * all class definitions starting with 'GPU*' are modules from the
  49801. * WebGPU API. So for example `BindGroup` is a class from the engine
  49802. * whereas `GPUBindGroup` is a class from WebGPU.
  49803. *
  49804. * @private
  49805. */
  49806. class WebGPUBindingUtils {
  49807. /**
  49808. * Constructs a new utility object.
  49809. *
  49810. * @param {WebGPUBackend} backend - The WebGPU backend.
  49811. */
  49812. constructor( backend ) {
  49813. /**
  49814. * A reference to the WebGPU backend.
  49815. *
  49816. * @type {WebGPUBackend}
  49817. */
  49818. this.backend = backend;
  49819. /**
  49820. * A cache for managing bind group layouts.
  49821. *
  49822. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  49823. */
  49824. this.bindGroupLayoutCache = new WeakMap();
  49825. }
  49826. /**
  49827. * Creates a GPU bind group layout for the given bind group.
  49828. *
  49829. * @param {BindGroup} bindGroup - The bind group.
  49830. * @return {GPUBindGroupLayout} The GPU bind group layout.
  49831. */
  49832. createBindingsLayout( bindGroup ) {
  49833. const backend = this.backend;
  49834. const device = backend.device;
  49835. const entries = [];
  49836. let index = 0;
  49837. for ( const binding of bindGroup.bindings ) {
  49838. const bindingGPU = {
  49839. binding: index ++,
  49840. visibility: binding.visibility
  49841. };
  49842. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  49843. const buffer = {}; // GPUBufferBindingLayout
  49844. if ( binding.isStorageBuffer ) {
  49845. if ( binding.visibility & 4 ) {
  49846. // compute
  49847. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  49848. buffer.type = GPUBufferBindingType.Storage;
  49849. } else {
  49850. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  49851. }
  49852. } else {
  49853. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  49854. }
  49855. }
  49856. bindingGPU.buffer = buffer;
  49857. } else if ( binding.isSampledTexture && binding.store ) {
  49858. const storageTexture = {}; // GPUStorageTextureBindingLayout
  49859. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  49860. const access = binding.access;
  49861. if ( access === NodeAccess.READ_WRITE ) {
  49862. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  49863. } else if ( access === NodeAccess.WRITE_ONLY ) {
  49864. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  49865. } else {
  49866. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  49867. }
  49868. if ( binding.texture.isArrayTexture ) {
  49869. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  49870. } else if ( binding.texture.is3DTexture ) {
  49871. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  49872. }
  49873. bindingGPU.storageTexture = storageTexture;
  49874. } else if ( binding.isSampledTexture ) {
  49875. const texture = {}; // GPUTextureBindingLayout
  49876. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  49877. if ( primarySamples > 1 ) {
  49878. texture.multisampled = true;
  49879. if ( ! binding.texture.isDepthTexture ) {
  49880. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49881. }
  49882. }
  49883. if ( binding.texture.isDepthTexture ) {
  49884. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  49885. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49886. } else {
  49887. texture.sampleType = GPUTextureSampleType.Depth;
  49888. }
  49889. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  49890. const type = binding.texture.type;
  49891. if ( type === IntType ) {
  49892. texture.sampleType = GPUTextureSampleType.SInt;
  49893. } else if ( type === UnsignedIntType ) {
  49894. texture.sampleType = GPUTextureSampleType.UInt;
  49895. } else if ( type === FloatType ) {
  49896. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  49897. texture.sampleType = GPUTextureSampleType.Float;
  49898. } else {
  49899. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49900. }
  49901. }
  49902. }
  49903. if ( binding.isSampledCubeTexture ) {
  49904. texture.viewDimension = GPUTextureViewDimension.Cube;
  49905. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  49906. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  49907. } else if ( binding.isSampledTexture3D ) {
  49908. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  49909. }
  49910. bindingGPU.texture = texture;
  49911. } else if ( binding.isSampler ) {
  49912. const sampler = {}; // GPUSamplerBindingLayout
  49913. if ( binding.texture.isDepthTexture ) {
  49914. if ( binding.texture.compareFunction !== null ) {
  49915. sampler.type = GPUSamplerBindingType.Comparison;
  49916. } else if ( backend.compatibilityMode ) {
  49917. sampler.type = GPUSamplerBindingType.NonFiltering;
  49918. }
  49919. }
  49920. bindingGPU.sampler = sampler;
  49921. } else {
  49922. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  49923. }
  49924. entries.push( bindingGPU );
  49925. }
  49926. return device.createBindGroupLayout( { entries } );
  49927. }
  49928. /**
  49929. * Creates bindings from the given bind group definition.
  49930. *
  49931. * @param {BindGroup} bindGroup - The bind group.
  49932. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49933. * @param {number} cacheIndex - The cache index.
  49934. * @param {number} version - The version.
  49935. */
  49936. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  49937. const { backend, bindGroupLayoutCache } = this;
  49938. const bindingsData = backend.get( bindGroup );
  49939. // setup (static) binding layout and (dynamic) binding group
  49940. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  49941. if ( bindLayoutGPU === undefined ) {
  49942. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  49943. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  49944. }
  49945. let bindGroupGPU;
  49946. if ( cacheIndex > 0 ) {
  49947. if ( bindingsData.groups === undefined ) {
  49948. bindingsData.groups = [];
  49949. bindingsData.versions = [];
  49950. }
  49951. if ( bindingsData.versions[ cacheIndex ] === version ) {
  49952. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  49953. }
  49954. }
  49955. if ( bindGroupGPU === undefined ) {
  49956. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  49957. if ( cacheIndex > 0 ) {
  49958. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  49959. bindingsData.versions[ cacheIndex ] = version;
  49960. }
  49961. }
  49962. bindingsData.group = bindGroupGPU;
  49963. bindingsData.layout = bindLayoutGPU;
  49964. }
  49965. /**
  49966. * Updates a buffer binding.
  49967. *
  49968. * @param {Buffer} binding - The buffer binding to update.
  49969. */
  49970. updateBinding( binding ) {
  49971. const backend = this.backend;
  49972. const device = backend.device;
  49973. const buffer = binding.buffer;
  49974. const bufferGPU = backend.get( binding ).buffer;
  49975. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  49976. }
  49977. /**
  49978. * Creates a GPU bind group for the camera index.
  49979. *
  49980. * @param {Uint32Array} data - The index data.
  49981. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  49982. * @return {GPUBindGroup} The GPU bind group.
  49983. */
  49984. createBindGroupIndex( data, layout ) {
  49985. const backend = this.backend;
  49986. const device = backend.device;
  49987. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  49988. const index = data[ 0 ];
  49989. const buffer = device.createBuffer( {
  49990. label: 'bindingCameraIndex_' + index,
  49991. size: 16, // uint(4) * 4
  49992. usage: usage
  49993. } );
  49994. device.queue.writeBuffer( buffer, 0, data, 0 );
  49995. const entries = [ { binding: 0, resource: { buffer } } ];
  49996. return device.createBindGroup( {
  49997. label: 'bindGroupCameraIndex_' + index,
  49998. layout,
  49999. entries
  50000. } );
  50001. }
  50002. /**
  50003. * Creates a GPU bind group for the given bind group and GPU layout.
  50004. *
  50005. * @param {BindGroup} bindGroup - The bind group.
  50006. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  50007. * @return {GPUBindGroup} The GPU bind group.
  50008. */
  50009. createBindGroup( bindGroup, layoutGPU ) {
  50010. const backend = this.backend;
  50011. const device = backend.device;
  50012. let bindingPoint = 0;
  50013. const entriesGPU = [];
  50014. for ( const binding of bindGroup.bindings ) {
  50015. if ( binding.isUniformBuffer ) {
  50016. const bindingData = backend.get( binding );
  50017. if ( bindingData.buffer === undefined ) {
  50018. const byteLength = binding.byteLength;
  50019. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  50020. const bufferGPU = device.createBuffer( {
  50021. label: 'bindingBuffer_' + binding.name,
  50022. size: byteLength,
  50023. usage: usage
  50024. } );
  50025. bindingData.buffer = bufferGPU;
  50026. }
  50027. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  50028. } else if ( binding.isStorageBuffer ) {
  50029. const bindingData = backend.get( binding );
  50030. if ( bindingData.buffer === undefined ) {
  50031. const attribute = binding.attribute;
  50032. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  50033. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  50034. bindingData.buffer = backend.get( attribute ).buffer;
  50035. }
  50036. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  50037. } else if ( binding.isSampledTexture ) {
  50038. const textureData = backend.get( binding.texture );
  50039. let resourceGPU;
  50040. if ( textureData.externalTexture !== undefined ) {
  50041. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  50042. } else {
  50043. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  50044. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  50045. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  50046. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  50047. }
  50048. propertyName += `-${ mipLevelCount }`;
  50049. resourceGPU = textureData[ propertyName ];
  50050. if ( resourceGPU === undefined ) {
  50051. const aspectGPU = GPUTextureAspect.All;
  50052. let dimensionViewGPU;
  50053. if ( binding.isSampledCubeTexture ) {
  50054. dimensionViewGPU = GPUTextureViewDimension.Cube;
  50055. } else if ( binding.isSampledTexture3D ) {
  50056. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  50057. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  50058. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  50059. } else {
  50060. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  50061. }
  50062. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  50063. }
  50064. }
  50065. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  50066. } else if ( binding.isSampler ) {
  50067. const textureGPU = backend.get( binding.texture );
  50068. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  50069. }
  50070. bindingPoint ++;
  50071. }
  50072. return device.createBindGroup( {
  50073. label: 'bindGroup_' + bindGroup.name,
  50074. layout: layoutGPU,
  50075. entries: entriesGPU
  50076. } );
  50077. }
  50078. }
  50079. /**
  50080. * A WebGPU backend utility module for managing pipelines.
  50081. *
  50082. * @private
  50083. */
  50084. class WebGPUPipelineUtils {
  50085. /**
  50086. * Constructs a new utility object.
  50087. *
  50088. * @param {WebGPUBackend} backend - The WebGPU backend.
  50089. */
  50090. constructor( backend ) {
  50091. /**
  50092. * A reference to the WebGPU backend.
  50093. *
  50094. * @type {WebGPUBackend}
  50095. */
  50096. this.backend = backend;
  50097. /**
  50098. * A Weak Map that tracks the active pipeline for render or compute passes.
  50099. *
  50100. * @private
  50101. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  50102. */
  50103. this._activePipelines = new WeakMap();
  50104. }
  50105. /**
  50106. * Sets the given pipeline for the given pass. The method makes sure to only set the
  50107. * pipeline when necessary.
  50108. *
  50109. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  50110. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  50111. */
  50112. setPipeline( pass, pipeline ) {
  50113. const currentPipeline = this._activePipelines.get( pass );
  50114. if ( currentPipeline !== pipeline ) {
  50115. pass.setPipeline( pipeline );
  50116. this._activePipelines.set( pass, pipeline );
  50117. }
  50118. }
  50119. /**
  50120. * Returns the sample count derived from the given render context.
  50121. *
  50122. * @private
  50123. * @param {RenderContext} renderContext - The render context.
  50124. * @return {number} The sample count.
  50125. */
  50126. _getSampleCount( renderContext ) {
  50127. return this.backend.utils.getSampleCountRenderContext( renderContext );
  50128. }
  50129. /**
  50130. * Creates a render pipeline for the given render object.
  50131. *
  50132. * @param {RenderObject} renderObject - The render object.
  50133. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  50134. */
  50135. createRenderPipeline( renderObject, promises ) {
  50136. const { object, material, geometry, pipeline } = renderObject;
  50137. const { vertexProgram, fragmentProgram } = pipeline;
  50138. const backend = this.backend;
  50139. const device = backend.device;
  50140. const utils = backend.utils;
  50141. const pipelineData = backend.get( pipeline );
  50142. // bind group layouts
  50143. const bindGroupLayouts = [];
  50144. for ( const bindGroup of renderObject.getBindings() ) {
  50145. const bindingsData = backend.get( bindGroup );
  50146. bindGroupLayouts.push( bindingsData.layout );
  50147. }
  50148. // vertex buffers
  50149. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  50150. // blending
  50151. let blending;
  50152. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  50153. blending = this._getBlending( material );
  50154. }
  50155. // stencil
  50156. let stencilFront = {};
  50157. if ( material.stencilWrite === true ) {
  50158. stencilFront = {
  50159. compare: this._getStencilCompare( material ),
  50160. failOp: this._getStencilOperation( material.stencilFail ),
  50161. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  50162. passOp: this._getStencilOperation( material.stencilZPass )
  50163. };
  50164. }
  50165. const colorWriteMask = this._getColorWriteMask( material );
  50166. const targets = [];
  50167. if ( renderObject.context.textures !== null ) {
  50168. const textures = renderObject.context.textures;
  50169. for ( let i = 0; i < textures.length; i ++ ) {
  50170. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  50171. targets.push( {
  50172. format: colorFormat,
  50173. blend: blending,
  50174. writeMask: colorWriteMask
  50175. } );
  50176. }
  50177. } else {
  50178. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  50179. targets.push( {
  50180. format: colorFormat,
  50181. blend: blending,
  50182. writeMask: colorWriteMask
  50183. } );
  50184. }
  50185. const vertexModule = backend.get( vertexProgram ).module;
  50186. const fragmentModule = backend.get( fragmentProgram ).module;
  50187. const primitiveState = this._getPrimitiveState( object, geometry, material );
  50188. const depthCompare = this._getDepthCompare( material );
  50189. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  50190. const sampleCount = this._getSampleCount( renderObject.context );
  50191. const pipelineDescriptor = {
  50192. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  50193. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  50194. fragment: Object.assign( {}, fragmentModule, { targets } ),
  50195. primitive: primitiveState,
  50196. multisample: {
  50197. count: sampleCount,
  50198. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  50199. },
  50200. layout: device.createPipelineLayout( {
  50201. bindGroupLayouts
  50202. } )
  50203. };
  50204. const depthStencil = {};
  50205. const renderDepth = renderObject.context.depth;
  50206. const renderStencil = renderObject.context.stencil;
  50207. if ( renderDepth === true || renderStencil === true ) {
  50208. if ( renderDepth === true ) {
  50209. depthStencil.format = depthStencilFormat;
  50210. depthStencil.depthWriteEnabled = material.depthWrite;
  50211. depthStencil.depthCompare = depthCompare;
  50212. }
  50213. if ( renderStencil === true ) {
  50214. depthStencil.stencilFront = stencilFront;
  50215. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  50216. depthStencil.stencilReadMask = material.stencilFuncMask;
  50217. depthStencil.stencilWriteMask = material.stencilWriteMask;
  50218. }
  50219. if ( material.polygonOffset === true ) {
  50220. depthStencil.depthBias = material.polygonOffsetUnits;
  50221. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  50222. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  50223. }
  50224. pipelineDescriptor.depthStencil = depthStencil;
  50225. }
  50226. if ( promises === null ) {
  50227. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  50228. } else {
  50229. const p = new Promise( ( resolve /*, reject*/ ) => {
  50230. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  50231. pipelineData.pipeline = pipeline;
  50232. resolve();
  50233. } );
  50234. } );
  50235. promises.push( p );
  50236. }
  50237. }
  50238. /**
  50239. * Creates GPU render bundle encoder for the given render context.
  50240. *
  50241. * @param {RenderContext} renderContext - The render context.
  50242. * @param {?string} [label='renderBundleEncoder'] - The label.
  50243. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  50244. */
  50245. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  50246. const backend = this.backend;
  50247. const { utils, device } = backend;
  50248. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  50249. const colorFormat = utils.getCurrentColorFormat( renderContext );
  50250. const sampleCount = this._getSampleCount( renderContext );
  50251. const descriptor = {
  50252. label: label,
  50253. colorFormats: [ colorFormat ],
  50254. depthStencilFormat,
  50255. sampleCount
  50256. };
  50257. return device.createRenderBundleEncoder( descriptor );
  50258. }
  50259. /**
  50260. * Creates a compute pipeline for the given compute node.
  50261. *
  50262. * @param {ComputePipeline} pipeline - The compute pipeline.
  50263. * @param {Array<BindGroup>} bindings - The bindings.
  50264. */
  50265. createComputePipeline( pipeline, bindings ) {
  50266. const backend = this.backend;
  50267. const device = backend.device;
  50268. const computeProgram = backend.get( pipeline.computeProgram ).module;
  50269. const pipelineGPU = backend.get( pipeline );
  50270. // bind group layouts
  50271. const bindGroupLayouts = [];
  50272. for ( const bindingsGroup of bindings ) {
  50273. const bindingsData = backend.get( bindingsGroup );
  50274. bindGroupLayouts.push( bindingsData.layout );
  50275. }
  50276. pipelineGPU.pipeline = device.createComputePipeline( {
  50277. compute: computeProgram,
  50278. layout: device.createPipelineLayout( {
  50279. bindGroupLayouts
  50280. } )
  50281. } );
  50282. }
  50283. /**
  50284. * Returns the blending state as a descriptor object required
  50285. * for the pipeline creation.
  50286. *
  50287. * @private
  50288. * @param {Material} material - The material.
  50289. * @return {Object} The blending state.
  50290. */
  50291. _getBlending( material ) {
  50292. let color, alpha;
  50293. const blending = material.blending;
  50294. const blendSrc = material.blendSrc;
  50295. const blendDst = material.blendDst;
  50296. const blendEquation = material.blendEquation;
  50297. if ( blending === CustomBlending ) {
  50298. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  50299. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  50300. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  50301. color = {
  50302. srcFactor: this._getBlendFactor( blendSrc ),
  50303. dstFactor: this._getBlendFactor( blendDst ),
  50304. operation: this._getBlendOperation( blendEquation )
  50305. };
  50306. alpha = {
  50307. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  50308. dstFactor: this._getBlendFactor( blendDstAlpha ),
  50309. operation: this._getBlendOperation( blendEquationAlpha )
  50310. };
  50311. } else {
  50312. const premultipliedAlpha = material.premultipliedAlpha;
  50313. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  50314. color = {
  50315. srcFactor: srcRGB,
  50316. dstFactor: dstRGB,
  50317. operation: GPUBlendOperation.Add
  50318. };
  50319. alpha = {
  50320. srcFactor: srcAlpha,
  50321. dstFactor: dstAlpha,
  50322. operation: GPUBlendOperation.Add
  50323. };
  50324. };
  50325. if ( premultipliedAlpha ) {
  50326. switch ( blending ) {
  50327. case NormalBlending:
  50328. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  50329. break;
  50330. case AdditiveBlending:
  50331. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  50332. break;
  50333. case SubtractiveBlending:
  50334. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  50335. break;
  50336. case MultiplyBlending:
  50337. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  50338. break;
  50339. }
  50340. } else {
  50341. switch ( blending ) {
  50342. case NormalBlending:
  50343. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  50344. break;
  50345. case AdditiveBlending:
  50346. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  50347. break;
  50348. case SubtractiveBlending:
  50349. console.error( 'THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  50350. break;
  50351. case MultiplyBlending:
  50352. console.error( 'THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  50353. break;
  50354. }
  50355. }
  50356. }
  50357. if ( color !== undefined && alpha !== undefined ) {
  50358. return { color, alpha };
  50359. } else {
  50360. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  50361. }
  50362. }
  50363. /**
  50364. * Returns the GPU blend factor which is required for the pipeline creation.
  50365. *
  50366. * @private
  50367. * @param {number} blend - The blend factor as a three.js constant.
  50368. * @return {string} The GPU blend factor.
  50369. */
  50370. _getBlendFactor( blend ) {
  50371. let blendFactor;
  50372. switch ( blend ) {
  50373. case ZeroFactor:
  50374. blendFactor = GPUBlendFactor.Zero;
  50375. break;
  50376. case OneFactor:
  50377. blendFactor = GPUBlendFactor.One;
  50378. break;
  50379. case SrcColorFactor:
  50380. blendFactor = GPUBlendFactor.Src;
  50381. break;
  50382. case OneMinusSrcColorFactor:
  50383. blendFactor = GPUBlendFactor.OneMinusSrc;
  50384. break;
  50385. case SrcAlphaFactor:
  50386. blendFactor = GPUBlendFactor.SrcAlpha;
  50387. break;
  50388. case OneMinusSrcAlphaFactor:
  50389. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  50390. break;
  50391. case DstColorFactor:
  50392. blendFactor = GPUBlendFactor.Dst;
  50393. break;
  50394. case OneMinusDstColorFactor:
  50395. blendFactor = GPUBlendFactor.OneMinusDst;
  50396. break;
  50397. case DstAlphaFactor:
  50398. blendFactor = GPUBlendFactor.DstAlpha;
  50399. break;
  50400. case OneMinusDstAlphaFactor:
  50401. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  50402. break;
  50403. case SrcAlphaSaturateFactor:
  50404. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  50405. break;
  50406. case BlendColorFactor:
  50407. blendFactor = GPUBlendFactor.Constant;
  50408. break;
  50409. case OneMinusBlendColorFactor:
  50410. blendFactor = GPUBlendFactor.OneMinusConstant;
  50411. break;
  50412. default:
  50413. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  50414. }
  50415. return blendFactor;
  50416. }
  50417. /**
  50418. * Returns the GPU stencil compare function which is required for the pipeline creation.
  50419. *
  50420. * @private
  50421. * @param {Material} material - The material.
  50422. * @return {string} The GPU stencil compare function.
  50423. */
  50424. _getStencilCompare( material ) {
  50425. let stencilCompare;
  50426. const stencilFunc = material.stencilFunc;
  50427. switch ( stencilFunc ) {
  50428. case NeverStencilFunc:
  50429. stencilCompare = GPUCompareFunction.Never;
  50430. break;
  50431. case AlwaysStencilFunc:
  50432. stencilCompare = GPUCompareFunction.Always;
  50433. break;
  50434. case LessStencilFunc:
  50435. stencilCompare = GPUCompareFunction.Less;
  50436. break;
  50437. case LessEqualStencilFunc:
  50438. stencilCompare = GPUCompareFunction.LessEqual;
  50439. break;
  50440. case EqualStencilFunc:
  50441. stencilCompare = GPUCompareFunction.Equal;
  50442. break;
  50443. case GreaterEqualStencilFunc:
  50444. stencilCompare = GPUCompareFunction.GreaterEqual;
  50445. break;
  50446. case GreaterStencilFunc:
  50447. stencilCompare = GPUCompareFunction.Greater;
  50448. break;
  50449. case NotEqualStencilFunc:
  50450. stencilCompare = GPUCompareFunction.NotEqual;
  50451. break;
  50452. default:
  50453. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  50454. }
  50455. return stencilCompare;
  50456. }
  50457. /**
  50458. * Returns the GPU stencil operation which is required for the pipeline creation.
  50459. *
  50460. * @private
  50461. * @param {number} op - A three.js constant defining the stencil operation.
  50462. * @return {string} The GPU stencil operation.
  50463. */
  50464. _getStencilOperation( op ) {
  50465. let stencilOperation;
  50466. switch ( op ) {
  50467. case KeepStencilOp:
  50468. stencilOperation = GPUStencilOperation.Keep;
  50469. break;
  50470. case ZeroStencilOp:
  50471. stencilOperation = GPUStencilOperation.Zero;
  50472. break;
  50473. case ReplaceStencilOp:
  50474. stencilOperation = GPUStencilOperation.Replace;
  50475. break;
  50476. case InvertStencilOp:
  50477. stencilOperation = GPUStencilOperation.Invert;
  50478. break;
  50479. case IncrementStencilOp:
  50480. stencilOperation = GPUStencilOperation.IncrementClamp;
  50481. break;
  50482. case DecrementStencilOp:
  50483. stencilOperation = GPUStencilOperation.DecrementClamp;
  50484. break;
  50485. case IncrementWrapStencilOp:
  50486. stencilOperation = GPUStencilOperation.IncrementWrap;
  50487. break;
  50488. case DecrementWrapStencilOp:
  50489. stencilOperation = GPUStencilOperation.DecrementWrap;
  50490. break;
  50491. default:
  50492. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  50493. }
  50494. return stencilOperation;
  50495. }
  50496. /**
  50497. * Returns the GPU blend operation which is required for the pipeline creation.
  50498. *
  50499. * @private
  50500. * @param {number} blendEquation - A three.js constant defining the blend equation.
  50501. * @return {string} The GPU blend operation.
  50502. */
  50503. _getBlendOperation( blendEquation ) {
  50504. let blendOperation;
  50505. switch ( blendEquation ) {
  50506. case AddEquation:
  50507. blendOperation = GPUBlendOperation.Add;
  50508. break;
  50509. case SubtractEquation:
  50510. blendOperation = GPUBlendOperation.Subtract;
  50511. break;
  50512. case ReverseSubtractEquation:
  50513. blendOperation = GPUBlendOperation.ReverseSubtract;
  50514. break;
  50515. case MinEquation:
  50516. blendOperation = GPUBlendOperation.Min;
  50517. break;
  50518. case MaxEquation:
  50519. blendOperation = GPUBlendOperation.Max;
  50520. break;
  50521. default:
  50522. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  50523. }
  50524. return blendOperation;
  50525. }
  50526. /**
  50527. * Returns the primitive state as a descriptor object required
  50528. * for the pipeline creation.
  50529. *
  50530. * @private
  50531. * @param {Object3D} object - The 3D object.
  50532. * @param {BufferGeometry} geometry - The geometry.
  50533. * @param {Material} material - The material.
  50534. * @return {Object} The primitive state.
  50535. */
  50536. _getPrimitiveState( object, geometry, material ) {
  50537. const descriptor = {};
  50538. const utils = this.backend.utils;
  50539. descriptor.topology = utils.getPrimitiveTopology( object, material );
  50540. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  50541. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  50542. }
  50543. switch ( material.side ) {
  50544. case FrontSide:
  50545. descriptor.frontFace = GPUFrontFace.CCW;
  50546. descriptor.cullMode = GPUCullMode.Back;
  50547. break;
  50548. case BackSide:
  50549. descriptor.frontFace = GPUFrontFace.CCW;
  50550. descriptor.cullMode = GPUCullMode.Front;
  50551. break;
  50552. case DoubleSide:
  50553. descriptor.frontFace = GPUFrontFace.CCW;
  50554. descriptor.cullMode = GPUCullMode.None;
  50555. break;
  50556. default:
  50557. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  50558. break;
  50559. }
  50560. return descriptor;
  50561. }
  50562. /**
  50563. * Returns the GPU color write mask which is required for the pipeline creation.
  50564. *
  50565. * @private
  50566. * @param {Material} material - The material.
  50567. * @return {number} The GPU color write mask.
  50568. */
  50569. _getColorWriteMask( material ) {
  50570. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  50571. }
  50572. /**
  50573. * Returns the GPU depth compare function which is required for the pipeline creation.
  50574. *
  50575. * @private
  50576. * @param {Material} material - The material.
  50577. * @return {string} The GPU depth compare function.
  50578. */
  50579. _getDepthCompare( material ) {
  50580. let depthCompare;
  50581. if ( material.depthTest === false ) {
  50582. depthCompare = GPUCompareFunction.Always;
  50583. } else {
  50584. const depthFunc = material.depthFunc;
  50585. switch ( depthFunc ) {
  50586. case NeverDepth:
  50587. depthCompare = GPUCompareFunction.Never;
  50588. break;
  50589. case AlwaysDepth:
  50590. depthCompare = GPUCompareFunction.Always;
  50591. break;
  50592. case LessDepth:
  50593. depthCompare = GPUCompareFunction.Less;
  50594. break;
  50595. case LessEqualDepth:
  50596. depthCompare = GPUCompareFunction.LessEqual;
  50597. break;
  50598. case EqualDepth:
  50599. depthCompare = GPUCompareFunction.Equal;
  50600. break;
  50601. case GreaterEqualDepth:
  50602. depthCompare = GPUCompareFunction.GreaterEqual;
  50603. break;
  50604. case GreaterDepth:
  50605. depthCompare = GPUCompareFunction.Greater;
  50606. break;
  50607. case NotEqualDepth:
  50608. depthCompare = GPUCompareFunction.NotEqual;
  50609. break;
  50610. default:
  50611. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  50612. }
  50613. }
  50614. return depthCompare;
  50615. }
  50616. }
  50617. /**
  50618. * Manages a pool of WebGPU timestamp queries for performance measurement.
  50619. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  50620. *
  50621. * @augments TimestampQueryPool
  50622. */
  50623. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  50624. /**
  50625. * Creates a new WebGPU timestamp query pool.
  50626. *
  50627. * @param {GPUDevice} device - The WebGPU device to create queries on.
  50628. * @param {string} type - The type identifier for this query pool.
  50629. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  50630. */
  50631. constructor( device, type, maxQueries = 2048 ) {
  50632. super( maxQueries );
  50633. this.device = device;
  50634. this.type = type;
  50635. this.querySet = this.device.createQuerySet( {
  50636. type: 'timestamp',
  50637. count: this.maxQueries,
  50638. label: `queryset_global_timestamp_${type}`
  50639. } );
  50640. const bufferSize = this.maxQueries * 8;
  50641. this.resolveBuffer = this.device.createBuffer( {
  50642. label: `buffer_timestamp_resolve_${type}`,
  50643. size: bufferSize,
  50644. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  50645. } );
  50646. this.resultBuffer = this.device.createBuffer( {
  50647. label: `buffer_timestamp_result_${type}`,
  50648. size: bufferSize,
  50649. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50650. } );
  50651. }
  50652. /**
  50653. * Allocates a pair of queries for a given render context.
  50654. *
  50655. * @param {Object} renderContext - The render context to allocate queries for.
  50656. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  50657. */
  50658. allocateQueriesForContext( renderContext ) {
  50659. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  50660. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  50661. 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() } ).` );
  50662. return null;
  50663. }
  50664. const baseOffset = this.currentQueryIndex;
  50665. this.currentQueryIndex += 2;
  50666. this.queryOffsets.set( renderContext.id, baseOffset );
  50667. return baseOffset;
  50668. }
  50669. /**
  50670. * Asynchronously resolves all pending queries and returns the total duration.
  50671. * If there's already a pending resolve operation, returns that promise instead.
  50672. *
  50673. * @async
  50674. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  50675. */
  50676. async resolveQueriesAsync() {
  50677. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  50678. return this.lastValue;
  50679. }
  50680. if ( this.pendingResolve ) {
  50681. return this.pendingResolve;
  50682. }
  50683. this.pendingResolve = this._resolveQueries();
  50684. try {
  50685. const result = await this.pendingResolve;
  50686. return result;
  50687. } finally {
  50688. this.pendingResolve = null;
  50689. }
  50690. }
  50691. /**
  50692. * Internal method to resolve queries and calculate total duration.
  50693. *
  50694. * @async
  50695. * @private
  50696. * @returns {Promise<number>} The total duration in milliseconds.
  50697. */
  50698. async _resolveQueries() {
  50699. if ( this.isDisposed ) {
  50700. return this.lastValue;
  50701. }
  50702. try {
  50703. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  50704. return this.lastValue;
  50705. }
  50706. const currentOffsets = new Map( this.queryOffsets );
  50707. const queryCount = this.currentQueryIndex;
  50708. const bytesUsed = queryCount * 8;
  50709. // Reset state before GPU work
  50710. this.currentQueryIndex = 0;
  50711. this.queryOffsets.clear();
  50712. const commandEncoder = this.device.createCommandEncoder();
  50713. commandEncoder.resolveQuerySet(
  50714. this.querySet,
  50715. 0,
  50716. queryCount,
  50717. this.resolveBuffer,
  50718. 0
  50719. );
  50720. commandEncoder.copyBufferToBuffer(
  50721. this.resolveBuffer,
  50722. 0,
  50723. this.resultBuffer,
  50724. 0,
  50725. bytesUsed
  50726. );
  50727. const commandBuffer = commandEncoder.finish();
  50728. this.device.queue.submit( [ commandBuffer ] );
  50729. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  50730. return this.lastValue;
  50731. }
  50732. // Create and track the mapping operation
  50733. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  50734. if ( this.isDisposed ) {
  50735. if ( this.resultBuffer.mapState === 'mapped' ) {
  50736. this.resultBuffer.unmap();
  50737. }
  50738. return this.lastValue;
  50739. }
  50740. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  50741. let totalDuration = 0;
  50742. for ( const [ , baseOffset ] of currentOffsets ) {
  50743. const startTime = times[ baseOffset ];
  50744. const endTime = times[ baseOffset + 1 ];
  50745. const duration = Number( endTime - startTime ) / 1e6;
  50746. totalDuration += duration;
  50747. }
  50748. this.resultBuffer.unmap();
  50749. this.lastValue = totalDuration;
  50750. return totalDuration;
  50751. } catch ( error ) {
  50752. console.error( 'Error resolving queries:', error );
  50753. if ( this.resultBuffer.mapState === 'mapped' ) {
  50754. this.resultBuffer.unmap();
  50755. }
  50756. return this.lastValue;
  50757. }
  50758. }
  50759. /**
  50760. * Dispose of the query pool.
  50761. *
  50762. * @async
  50763. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  50764. */
  50765. async dispose() {
  50766. if ( this.isDisposed ) {
  50767. return;
  50768. }
  50769. this.isDisposed = true;
  50770. // Wait for pending resolve operation
  50771. if ( this.pendingResolve ) {
  50772. try {
  50773. await this.pendingResolve;
  50774. } catch ( error ) {
  50775. console.error( 'Error waiting for pending resolve:', error );
  50776. }
  50777. }
  50778. // Ensure buffer is unmapped before destroying
  50779. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  50780. try {
  50781. this.resultBuffer.unmap();
  50782. } catch ( error ) {
  50783. console.error( 'Error unmapping buffer:', error );
  50784. }
  50785. }
  50786. // Destroy resources
  50787. if ( this.querySet ) {
  50788. this.querySet.destroy();
  50789. this.querySet = null;
  50790. }
  50791. if ( this.resolveBuffer ) {
  50792. this.resolveBuffer.destroy();
  50793. this.resolveBuffer = null;
  50794. }
  50795. if ( this.resultBuffer ) {
  50796. this.resultBuffer.destroy();
  50797. this.resultBuffer = null;
  50798. }
  50799. this.queryOffsets.clear();
  50800. this.pendingResolve = null;
  50801. }
  50802. }
  50803. /*// debugger tools
  50804. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  50805. //*/
  50806. /**
  50807. * A backend implementation targeting WebGPU.
  50808. *
  50809. * @private
  50810. * @augments Backend
  50811. */
  50812. class WebGPUBackend extends Backend {
  50813. /**
  50814. * WebGPUBackend options.
  50815. *
  50816. * @typedef {Object} WebGPUBackend~Options
  50817. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  50818. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  50819. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  50820. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  50821. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  50822. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  50823. * @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.
  50824. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  50825. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  50826. * @property {string} [powerPreference=undefined] - The power preference.
  50827. * @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.
  50828. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  50829. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  50830. */
  50831. /**
  50832. * Constructs a new WebGPU backend.
  50833. *
  50834. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  50835. */
  50836. constructor( parameters = {} ) {
  50837. super( parameters );
  50838. /**
  50839. * This flag can be used for type testing.
  50840. *
  50841. * @type {boolean}
  50842. * @readonly
  50843. * @default true
  50844. */
  50845. this.isWebGPUBackend = true;
  50846. // some parameters require default values other than "undefined"
  50847. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  50848. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  50849. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  50850. /**
  50851. * Indicates whether the backend is in compatibility mode or not.
  50852. * @type {boolean}
  50853. * @default false
  50854. */
  50855. this.compatibilityMode = this.parameters.compatibilityMode;
  50856. /**
  50857. * A reference to the device.
  50858. *
  50859. * @type {?GPUDevice}
  50860. * @default null
  50861. */
  50862. this.device = null;
  50863. /**
  50864. * A reference to the context.
  50865. *
  50866. * @type {?GPUCanvasContext}
  50867. * @default null
  50868. */
  50869. this.context = null;
  50870. /**
  50871. * A reference to the color attachment of the default framebuffer.
  50872. *
  50873. * @type {?GPUTexture}
  50874. * @default null
  50875. */
  50876. this.colorBuffer = null;
  50877. /**
  50878. * A reference to the default render pass descriptor.
  50879. *
  50880. * @type {?Object}
  50881. * @default null
  50882. */
  50883. this.defaultRenderPassdescriptor = null;
  50884. /**
  50885. * A reference to a backend module holding common utility functions.
  50886. *
  50887. * @type {WebGPUUtils}
  50888. */
  50889. this.utils = new WebGPUUtils( this );
  50890. /**
  50891. * A reference to a backend module holding shader attribute-related
  50892. * utility functions.
  50893. *
  50894. * @type {WebGPUAttributeUtils}
  50895. */
  50896. this.attributeUtils = new WebGPUAttributeUtils( this );
  50897. /**
  50898. * A reference to a backend module holding shader binding-related
  50899. * utility functions.
  50900. *
  50901. * @type {WebGPUBindingUtils}
  50902. */
  50903. this.bindingUtils = new WebGPUBindingUtils( this );
  50904. /**
  50905. * A reference to a backend module holding shader pipeline-related
  50906. * utility functions.
  50907. *
  50908. * @type {WebGPUPipelineUtils}
  50909. */
  50910. this.pipelineUtils = new WebGPUPipelineUtils( this );
  50911. /**
  50912. * A reference to a backend module holding shader texture-related
  50913. * utility functions.
  50914. *
  50915. * @type {WebGPUTextureUtils}
  50916. */
  50917. this.textureUtils = new WebGPUTextureUtils( this );
  50918. /**
  50919. * A map that manages the resolve buffers for occlusion queries.
  50920. *
  50921. * @type {Map<number,GPUBuffer>}
  50922. */
  50923. this.occludedResolveCache = new Map();
  50924. }
  50925. /**
  50926. * Initializes the backend so it is ready for usage.
  50927. *
  50928. * @async
  50929. * @param {Renderer} renderer - The renderer.
  50930. * @return {Promise} A Promise that resolves when the backend has been initialized.
  50931. */
  50932. async init( renderer ) {
  50933. await super.init( renderer );
  50934. //
  50935. const parameters = this.parameters;
  50936. // create the device if it is not passed with parameters
  50937. let device;
  50938. if ( parameters.device === undefined ) {
  50939. const adapterOptions = {
  50940. powerPreference: parameters.powerPreference,
  50941. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  50942. };
  50943. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  50944. if ( adapter === null ) {
  50945. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  50946. }
  50947. // feature support
  50948. const features = Object.values( GPUFeatureName );
  50949. const supportedFeatures = [];
  50950. for ( const name of features ) {
  50951. if ( adapter.features.has( name ) ) {
  50952. supportedFeatures.push( name );
  50953. }
  50954. }
  50955. const deviceDescriptor = {
  50956. requiredFeatures: supportedFeatures,
  50957. requiredLimits: parameters.requiredLimits
  50958. };
  50959. device = await adapter.requestDevice( deviceDescriptor );
  50960. } else {
  50961. device = parameters.device;
  50962. }
  50963. device.lost.then( ( info ) => {
  50964. const deviceLossInfo = {
  50965. api: 'WebGPU',
  50966. message: info.message || 'Unknown reason',
  50967. reason: info.reason || null,
  50968. originalEvent: info
  50969. };
  50970. renderer.onDeviceLost( deviceLossInfo );
  50971. } );
  50972. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  50973. this.device = device;
  50974. this.context = context;
  50975. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  50976. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  50977. this.context.configure( {
  50978. device: this.device,
  50979. format: this.utils.getPreferredCanvasFormat(),
  50980. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  50981. alphaMode: alphaMode
  50982. } );
  50983. this.updateSize();
  50984. }
  50985. /**
  50986. * The coordinate system of the backend.
  50987. *
  50988. * @type {number}
  50989. * @readonly
  50990. */
  50991. get coordinateSystem() {
  50992. return WebGPUCoordinateSystem;
  50993. }
  50994. /**
  50995. * This method performs a readback operation by moving buffer data from
  50996. * a storage buffer attribute from the GPU to the CPU.
  50997. *
  50998. * @async
  50999. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  51000. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  51001. */
  51002. async getArrayBufferAsync( attribute ) {
  51003. return await this.attributeUtils.getArrayBufferAsync( attribute );
  51004. }
  51005. /**
  51006. * Returns the backend's rendering context.
  51007. *
  51008. * @return {GPUCanvasContext} The rendering context.
  51009. */
  51010. getContext() {
  51011. return this.context;
  51012. }
  51013. /**
  51014. * Returns the default render pass descriptor.
  51015. *
  51016. * In WebGPU, the default framebuffer must be configured
  51017. * like custom framebuffers so the backend needs a render
  51018. * pass descriptor even when rendering directly to screen.
  51019. *
  51020. * @private
  51021. * @return {Object} The render pass descriptor.
  51022. */
  51023. _getDefaultRenderPassDescriptor() {
  51024. let descriptor = this.defaultRenderPassdescriptor;
  51025. if ( descriptor === null ) {
  51026. const renderer = this.renderer;
  51027. descriptor = {
  51028. colorAttachments: [ {
  51029. view: null
  51030. } ],
  51031. };
  51032. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  51033. descriptor.depthStencilAttachment = {
  51034. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  51035. };
  51036. }
  51037. const colorAttachment = descriptor.colorAttachments[ 0 ];
  51038. if ( this.renderer.samples > 0 ) {
  51039. colorAttachment.view = this.colorBuffer.createView();
  51040. } else {
  51041. colorAttachment.resolveTarget = undefined;
  51042. }
  51043. this.defaultRenderPassdescriptor = descriptor;
  51044. }
  51045. const colorAttachment = descriptor.colorAttachments[ 0 ];
  51046. if ( this.renderer.samples > 0 ) {
  51047. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  51048. } else {
  51049. colorAttachment.view = this.context.getCurrentTexture().createView();
  51050. }
  51051. return descriptor;
  51052. }
  51053. /**
  51054. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  51055. *
  51056. * @param {RenderContext} renderContext - The render context.
  51057. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  51058. *
  51059. * @private
  51060. */
  51061. _isRenderCameraDepthArray( renderContext ) {
  51062. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  51063. }
  51064. /**
  51065. * Returns the render pass descriptor for the given render context.
  51066. *
  51067. * @private
  51068. * @param {RenderContext} renderContext - The render context.
  51069. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  51070. * @return {Object} The render pass descriptor.
  51071. */
  51072. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  51073. const renderTarget = renderContext.renderTarget;
  51074. const renderTargetData = this.get( renderTarget );
  51075. let descriptors = renderTargetData.descriptors;
  51076. if ( descriptors === undefined ||
  51077. renderTargetData.width !== renderTarget.width ||
  51078. renderTargetData.height !== renderTarget.height ||
  51079. renderTargetData.dimensions !== renderTarget.dimensions ||
  51080. renderTargetData.activeMipmapLevel !== renderContext.activeMipmapLevel ||
  51081. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  51082. renderTargetData.samples !== renderTarget.samples
  51083. ) {
  51084. descriptors = {};
  51085. renderTargetData.descriptors = descriptors;
  51086. // dispose
  51087. const onDispose = () => {
  51088. renderTarget.removeEventListener( 'dispose', onDispose );
  51089. this.delete( renderTarget );
  51090. };
  51091. if ( renderTarget.hasEventListener( 'dispose', onDispose ) === false ) {
  51092. renderTarget.addEventListener( 'dispose', onDispose );
  51093. }
  51094. }
  51095. const cacheKey = renderContext.getCacheKey();
  51096. let descriptorBase = descriptors[ cacheKey ];
  51097. if ( descriptorBase === undefined ) {
  51098. const textures = renderContext.textures;
  51099. const textureViews = [];
  51100. let sliceIndex;
  51101. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  51102. for ( let i = 0; i < textures.length; i ++ ) {
  51103. const textureData = this.get( textures[ i ] );
  51104. const viewDescriptor = {
  51105. label: `colorAttachment_${ i }`,
  51106. baseMipLevel: renderContext.activeMipmapLevel,
  51107. mipLevelCount: 1,
  51108. baseArrayLayer: renderContext.activeCubeFace,
  51109. arrayLayerCount: 1,
  51110. dimension: GPUTextureViewDimension.TwoD
  51111. };
  51112. if ( renderTarget.isRenderTarget3D ) {
  51113. sliceIndex = renderContext.activeCubeFace;
  51114. viewDescriptor.baseArrayLayer = 0;
  51115. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  51116. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  51117. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  51118. if ( isRenderCameraDepthArray === true ) {
  51119. const cameras = renderContext.camera.cameras;
  51120. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  51121. const layerViewDescriptor = {
  51122. ...viewDescriptor,
  51123. baseArrayLayer: layer,
  51124. arrayLayerCount: 1,
  51125. dimension: GPUTextureViewDimension.TwoD
  51126. };
  51127. const textureView = textureData.texture.createView( layerViewDescriptor );
  51128. textureViews.push( {
  51129. view: textureView,
  51130. resolveTarget: undefined,
  51131. depthSlice: undefined
  51132. } );
  51133. }
  51134. } else {
  51135. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  51136. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  51137. }
  51138. }
  51139. if ( isRenderCameraDepthArray !== true ) {
  51140. const textureView = textureData.texture.createView( viewDescriptor );
  51141. let view, resolveTarget;
  51142. if ( textureData.msaaTexture !== undefined ) {
  51143. view = textureData.msaaTexture.createView();
  51144. resolveTarget = textureView;
  51145. } else {
  51146. view = textureView;
  51147. resolveTarget = undefined;
  51148. }
  51149. textureViews.push( {
  51150. view,
  51151. resolveTarget,
  51152. depthSlice: sliceIndex
  51153. } );
  51154. }
  51155. }
  51156. descriptorBase = { textureViews };
  51157. if ( renderContext.depth ) {
  51158. const depthTextureData = this.get( renderContext.depthTexture );
  51159. const options = {};
  51160. if ( renderContext.depthTexture.isArrayTexture ) {
  51161. options.dimension = GPUTextureViewDimension.TwoD;
  51162. options.arrayLayerCount = 1;
  51163. options.baseArrayLayer = renderContext.activeCubeFace;
  51164. }
  51165. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  51166. }
  51167. descriptors[ cacheKey ] = descriptorBase;
  51168. renderTargetData.width = renderTarget.width;
  51169. renderTargetData.height = renderTarget.height;
  51170. renderTargetData.samples = renderTarget.samples;
  51171. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  51172. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  51173. renderTargetData.dimensions = renderTarget.dimensions;
  51174. }
  51175. const descriptor = {
  51176. colorAttachments: []
  51177. };
  51178. // Apply dynamic properties to cached views
  51179. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  51180. const viewInfo = descriptorBase.textureViews[ i ];
  51181. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  51182. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  51183. clearValue = colorAttachmentsConfig.clearValue;
  51184. }
  51185. descriptor.colorAttachments.push( {
  51186. view: viewInfo.view,
  51187. depthSlice: viewInfo.depthSlice,
  51188. resolveTarget: viewInfo.resolveTarget,
  51189. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  51190. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  51191. clearValue: clearValue
  51192. } );
  51193. }
  51194. if ( descriptorBase.depthStencilView ) {
  51195. descriptor.depthStencilAttachment = {
  51196. view: descriptorBase.depthStencilView
  51197. };
  51198. }
  51199. return descriptor;
  51200. }
  51201. /**
  51202. * This method is executed at the beginning of a render call and prepares
  51203. * the WebGPU state for upcoming render calls
  51204. *
  51205. * @param {RenderContext} renderContext - The render context.
  51206. */
  51207. beginRender( renderContext ) {
  51208. const renderContextData = this.get( renderContext );
  51209. const device = this.device;
  51210. const occlusionQueryCount = renderContext.occlusionQueryCount;
  51211. let occlusionQuerySet;
  51212. if ( occlusionQueryCount > 0 ) {
  51213. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  51214. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  51215. // Get a reference to the array of objects with queries. The renderContextData property
  51216. // can be changed by another render pass before the buffer.mapAsyc() completes.
  51217. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  51218. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  51219. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  51220. //
  51221. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  51222. renderContextData.occlusionQuerySet = occlusionQuerySet;
  51223. renderContextData.occlusionQueryIndex = 0;
  51224. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  51225. renderContextData.lastOcclusionObject = null;
  51226. }
  51227. let descriptor;
  51228. if ( renderContext.textures === null ) {
  51229. descriptor = this._getDefaultRenderPassDescriptor();
  51230. } else {
  51231. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  51232. }
  51233. this.initTimestampQuery( renderContext, descriptor );
  51234. descriptor.occlusionQuerySet = occlusionQuerySet;
  51235. const depthStencilAttachment = descriptor.depthStencilAttachment;
  51236. if ( renderContext.textures !== null ) {
  51237. const colorAttachments = descriptor.colorAttachments;
  51238. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  51239. const colorAttachment = colorAttachments[ i ];
  51240. if ( renderContext.clearColor ) {
  51241. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  51242. colorAttachment.loadOp = GPULoadOp.Clear;
  51243. } else {
  51244. colorAttachment.loadOp = GPULoadOp.Load;
  51245. }
  51246. colorAttachment.storeOp = GPUStoreOp.Store;
  51247. }
  51248. } else {
  51249. const colorAttachment = descriptor.colorAttachments[ 0 ];
  51250. if ( renderContext.clearColor ) {
  51251. colorAttachment.clearValue = renderContext.clearColorValue;
  51252. colorAttachment.loadOp = GPULoadOp.Clear;
  51253. } else {
  51254. colorAttachment.loadOp = GPULoadOp.Load;
  51255. }
  51256. colorAttachment.storeOp = GPUStoreOp.Store;
  51257. }
  51258. //
  51259. if ( renderContext.depth ) {
  51260. if ( renderContext.clearDepth ) {
  51261. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  51262. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  51263. } else {
  51264. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  51265. }
  51266. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  51267. }
  51268. if ( renderContext.stencil ) {
  51269. if ( renderContext.clearStencil ) {
  51270. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  51271. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  51272. } else {
  51273. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  51274. }
  51275. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  51276. }
  51277. //
  51278. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  51279. // shadow arrays - prepare bundle encoders for each camera in an array camera
  51280. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  51281. const cameras = renderContext.camera.cameras;
  51282. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  51283. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  51284. } else {
  51285. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  51286. }
  51287. // Create bundle encoders for each layer
  51288. renderContextData.bundleEncoders = [];
  51289. renderContextData.bundleSets = [];
  51290. // Create separate bundle encoders for each camera in the array
  51291. for ( let i = 0; i < cameras.length; i ++ ) {
  51292. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  51293. renderContext,
  51294. 'renderBundleArrayCamera_' + i
  51295. );
  51296. // Initialize state tracking for this bundle
  51297. const bundleSets = {
  51298. attributes: {},
  51299. bindingGroups: [],
  51300. pipeline: null,
  51301. index: null
  51302. };
  51303. renderContextData.bundleEncoders.push( bundleEncoder );
  51304. renderContextData.bundleSets.push( bundleSets );
  51305. }
  51306. // We'll complete the bundles in finishRender
  51307. renderContextData.currentPass = null;
  51308. } else {
  51309. const currentPass = encoder.beginRenderPass( descriptor );
  51310. renderContextData.currentPass = currentPass;
  51311. if ( renderContext.viewport ) {
  51312. this.updateViewport( renderContext );
  51313. }
  51314. if ( renderContext.scissor ) {
  51315. const { x, y, width, height } = renderContext.scissorValue;
  51316. currentPass.setScissorRect( x, y, width, height );
  51317. }
  51318. }
  51319. //
  51320. renderContextData.descriptor = descriptor;
  51321. renderContextData.encoder = encoder;
  51322. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  51323. renderContextData.renderBundles = [];
  51324. }
  51325. /**
  51326. * This method creates layer descriptors for each camera in an array camera
  51327. * to prepare for rendering to a depth array texture.
  51328. *
  51329. * @param {RenderContext} renderContext - The render context.
  51330. * @param {Object} renderContextData - The render context data.
  51331. * @param {Object} descriptor - The render pass descriptor.
  51332. * @param {ArrayCamera} cameras - The array camera.
  51333. *
  51334. * @private
  51335. */
  51336. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  51337. const depthStencilAttachment = descriptor.depthStencilAttachment;
  51338. renderContextData.layerDescriptors = [];
  51339. const depthTextureData = this.get( renderContext.depthTexture );
  51340. if ( ! depthTextureData.viewCache ) {
  51341. depthTextureData.viewCache = [];
  51342. }
  51343. for ( let i = 0; i < cameras.length; i ++ ) {
  51344. const layerDescriptor = {
  51345. ...descriptor,
  51346. colorAttachments: [ {
  51347. ...descriptor.colorAttachments[ 0 ],
  51348. view: descriptor.colorAttachments[ i ].view
  51349. } ]
  51350. };
  51351. if ( descriptor.depthStencilAttachment ) {
  51352. const layerIndex = i;
  51353. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  51354. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  51355. dimension: GPUTextureViewDimension.TwoD,
  51356. baseArrayLayer: i,
  51357. arrayLayerCount: 1
  51358. } );
  51359. }
  51360. layerDescriptor.depthStencilAttachment = {
  51361. view: depthTextureData.viewCache[ layerIndex ],
  51362. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  51363. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  51364. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  51365. };
  51366. if ( renderContext.stencil ) {
  51367. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  51368. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  51369. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  51370. }
  51371. } else {
  51372. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  51373. }
  51374. renderContextData.layerDescriptors.push( layerDescriptor );
  51375. }
  51376. }
  51377. /**
  51378. * This method updates the layer descriptors for each camera in an array camera
  51379. * to prepare for rendering to a depth array texture.
  51380. *
  51381. * @param {RenderContext} renderContext - The render context.
  51382. * @param {Object} renderContextData - The render context data.
  51383. * @param {ArrayCamera} cameras - The array camera.
  51384. *
  51385. */
  51386. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  51387. for ( let i = 0; i < cameras.length; i ++ ) {
  51388. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  51389. if ( layerDescriptor.depthStencilAttachment ) {
  51390. const depthAttachment = layerDescriptor.depthStencilAttachment;
  51391. if ( renderContext.depth ) {
  51392. if ( renderContext.clearDepth ) {
  51393. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  51394. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  51395. } else {
  51396. depthAttachment.depthLoadOp = GPULoadOp.Load;
  51397. }
  51398. }
  51399. if ( renderContext.stencil ) {
  51400. if ( renderContext.clearStencil ) {
  51401. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  51402. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  51403. } else {
  51404. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  51405. }
  51406. }
  51407. }
  51408. }
  51409. }
  51410. /**
  51411. * This method is executed at the end of a render call and finalizes work
  51412. * after draw calls.
  51413. *
  51414. * @param {RenderContext} renderContext - The render context.
  51415. */
  51416. finishRender( renderContext ) {
  51417. const renderContextData = this.get( renderContext );
  51418. const occlusionQueryCount = renderContext.occlusionQueryCount;
  51419. if ( renderContextData.renderBundles.length > 0 ) {
  51420. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  51421. }
  51422. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  51423. renderContextData.currentPass.endOcclusionQuery();
  51424. }
  51425. // shadow arrays - Execute bundles for each layer
  51426. const encoder = renderContextData.encoder;
  51427. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  51428. const bundles = [];
  51429. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  51430. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  51431. bundles.push( bundleEncoder.finish() );
  51432. }
  51433. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  51434. if ( i < bundles.length ) {
  51435. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  51436. const renderPass = encoder.beginRenderPass( layerDescriptor );
  51437. if ( renderContext.viewport ) {
  51438. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  51439. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  51440. }
  51441. if ( renderContext.scissor ) {
  51442. const { x, y, width, height } = renderContext.scissorValue;
  51443. renderPass.setScissorRect( x, y, width, height );
  51444. }
  51445. renderPass.executeBundles( [ bundles[ i ] ] );
  51446. renderPass.end();
  51447. }
  51448. }
  51449. } else if ( renderContextData.currentPass ) {
  51450. renderContextData.currentPass.end();
  51451. }
  51452. if ( occlusionQueryCount > 0 ) {
  51453. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  51454. //
  51455. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  51456. if ( queryResolveBuffer === undefined ) {
  51457. queryResolveBuffer = this.device.createBuffer(
  51458. {
  51459. size: bufferSize,
  51460. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  51461. }
  51462. );
  51463. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  51464. }
  51465. //
  51466. const readBuffer = this.device.createBuffer(
  51467. {
  51468. size: bufferSize,
  51469. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51470. }
  51471. );
  51472. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  51473. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  51474. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  51475. renderContextData.occlusionQueryBuffer = readBuffer;
  51476. //
  51477. this.resolveOccludedAsync( renderContext );
  51478. }
  51479. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  51480. //
  51481. if ( renderContext.textures !== null ) {
  51482. const textures = renderContext.textures;
  51483. for ( let i = 0; i < textures.length; i ++ ) {
  51484. const texture = textures[ i ];
  51485. if ( texture.generateMipmaps === true ) {
  51486. this.textureUtils.generateMipmaps( texture );
  51487. }
  51488. }
  51489. }
  51490. }
  51491. /**
  51492. * Returns `true` if the given 3D object is fully occluded by other
  51493. * 3D objects in the scene.
  51494. *
  51495. * @param {RenderContext} renderContext - The render context.
  51496. * @param {Object3D} object - The 3D object to test.
  51497. * @return {boolean} Whether the 3D object is fully occluded or not.
  51498. */
  51499. isOccluded( renderContext, object ) {
  51500. const renderContextData = this.get( renderContext );
  51501. return renderContextData.occluded && renderContextData.occluded.has( object );
  51502. }
  51503. /**
  51504. * This method processes the result of occlusion queries and writes it
  51505. * into render context data.
  51506. *
  51507. * @async
  51508. * @param {RenderContext} renderContext - The render context.
  51509. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  51510. */
  51511. async resolveOccludedAsync( renderContext ) {
  51512. const renderContextData = this.get( renderContext );
  51513. // handle occlusion query results
  51514. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  51515. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  51516. const occluded = new WeakSet();
  51517. renderContextData.currentOcclusionQueryObjects = null;
  51518. renderContextData.currentOcclusionQueryBuffer = null;
  51519. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  51520. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  51521. const results = new BigUint64Array( buffer );
  51522. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  51523. if ( results[ i ] === BigInt( 0 ) ) {
  51524. occluded.add( currentOcclusionQueryObjects[ i ] );
  51525. }
  51526. }
  51527. currentOcclusionQueryBuffer.destroy();
  51528. renderContextData.occluded = occluded;
  51529. }
  51530. }
  51531. /**
  51532. * Updates the viewport with the values from the given render context.
  51533. *
  51534. * @param {RenderContext} renderContext - The render context.
  51535. */
  51536. updateViewport( renderContext ) {
  51537. const { currentPass } = this.get( renderContext );
  51538. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  51539. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  51540. }
  51541. /**
  51542. * Returns the clear color and alpha into a single
  51543. * color object.
  51544. *
  51545. * @return {Color4} The clear color.
  51546. */
  51547. getClearColor() {
  51548. const clearColor = super.getClearColor();
  51549. // only premultiply alpha when alphaMode is "premultiplied"
  51550. if ( this.renderer.alpha === true ) {
  51551. clearColor.r *= clearColor.a;
  51552. clearColor.g *= clearColor.a;
  51553. clearColor.b *= clearColor.a;
  51554. }
  51555. return clearColor;
  51556. }
  51557. /**
  51558. * Performs a clear operation.
  51559. *
  51560. * @param {boolean} color - Whether the color buffer should be cleared or not.
  51561. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  51562. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  51563. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  51564. */
  51565. clear( color, depth, stencil, renderTargetContext = null ) {
  51566. const device = this.device;
  51567. const renderer = this.renderer;
  51568. let colorAttachments = [];
  51569. let depthStencilAttachment;
  51570. let clearValue;
  51571. let supportsDepth;
  51572. let supportsStencil;
  51573. if ( color ) {
  51574. const clearColor = this.getClearColor();
  51575. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  51576. }
  51577. if ( renderTargetContext === null ) {
  51578. supportsDepth = renderer.depth;
  51579. supportsStencil = renderer.stencil;
  51580. const descriptor = this._getDefaultRenderPassDescriptor();
  51581. if ( color ) {
  51582. colorAttachments = descriptor.colorAttachments;
  51583. const colorAttachment = colorAttachments[ 0 ];
  51584. colorAttachment.clearValue = clearValue;
  51585. colorAttachment.loadOp = GPULoadOp.Clear;
  51586. colorAttachment.storeOp = GPUStoreOp.Store;
  51587. }
  51588. if ( supportsDepth || supportsStencil ) {
  51589. depthStencilAttachment = descriptor.depthStencilAttachment;
  51590. }
  51591. } else {
  51592. supportsDepth = renderTargetContext.depth;
  51593. supportsStencil = renderTargetContext.stencil;
  51594. const clearConfig = {
  51595. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  51596. clearValue: color ? clearValue : undefined
  51597. };
  51598. if ( supportsDepth ) {
  51599. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  51600. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  51601. clearConfig.depthStoreOp = GPUStoreOp.Store;
  51602. }
  51603. if ( supportsStencil ) {
  51604. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  51605. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  51606. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  51607. }
  51608. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  51609. colorAttachments = descriptor.colorAttachments;
  51610. depthStencilAttachment = descriptor.depthStencilAttachment;
  51611. }
  51612. if ( supportsDepth && depthStencilAttachment ) {
  51613. if ( depth ) {
  51614. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  51615. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  51616. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  51617. } else {
  51618. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  51619. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  51620. }
  51621. }
  51622. //
  51623. if ( supportsStencil && depthStencilAttachment ) {
  51624. if ( stencil ) {
  51625. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  51626. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  51627. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  51628. } else {
  51629. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  51630. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  51631. }
  51632. }
  51633. //
  51634. const encoder = device.createCommandEncoder( { label: 'clear' } );
  51635. const currentPass = encoder.beginRenderPass( {
  51636. colorAttachments,
  51637. depthStencilAttachment
  51638. } );
  51639. currentPass.end();
  51640. device.queue.submit( [ encoder.finish() ] );
  51641. }
  51642. // compute
  51643. /**
  51644. * This method is executed at the beginning of a compute call and
  51645. * prepares the state for upcoming compute tasks.
  51646. *
  51647. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  51648. */
  51649. beginCompute( computeGroup ) {
  51650. const groupGPU = this.get( computeGroup );
  51651. const descriptor = {
  51652. label: 'computeGroup_' + computeGroup.id
  51653. };
  51654. this.initTimestampQuery( computeGroup, descriptor );
  51655. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  51656. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  51657. }
  51658. /**
  51659. * Executes a compute command for the given compute node.
  51660. *
  51661. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  51662. * @param {Node} computeNode - The compute node.
  51663. * @param {Array<BindGroup>} bindings - The bindings.
  51664. * @param {ComputePipeline} pipeline - The compute pipeline.
  51665. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  51666. */
  51667. compute( computeGroup, computeNode, bindings, pipeline, dispatchSizeOrCount = null ) {
  51668. const computeNodeData = this.get( computeNode );
  51669. const { passEncoderGPU } = this.get( computeGroup );
  51670. // pipeline
  51671. const pipelineGPU = this.get( pipeline ).pipeline;
  51672. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  51673. // bind groups
  51674. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  51675. const bindGroup = bindings[ i ];
  51676. const bindingsData = this.get( bindGroup );
  51677. passEncoderGPU.setBindGroup( i, bindingsData.group );
  51678. }
  51679. let dispatchSize;
  51680. if ( dispatchSizeOrCount === null ) {
  51681. dispatchSizeOrCount = computeNode.count;
  51682. }
  51683. if ( typeof dispatchSizeOrCount === 'number' ) {
  51684. // If a single number is given, we calculate the dispatch size based on the workgroup size
  51685. const count = dispatchSizeOrCount;
  51686. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  51687. // cache dispatch size to avoid recalculating it every time
  51688. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  51689. computeNodeData.count = count;
  51690. const workgroupSize = computeNode.workgroupSize;
  51691. let size = workgroupSize[ 0 ];
  51692. for ( let i = 1; i < workgroupSize.length; i ++ )
  51693. size *= workgroupSize[ i ];
  51694. const dispatchCount = Math.ceil( count / size );
  51695. //
  51696. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  51697. dispatchSize = [ dispatchCount, 1, 1 ];
  51698. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  51699. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  51700. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  51701. }
  51702. computeNodeData.dispatchSize = dispatchSize;
  51703. }
  51704. dispatchSize = computeNodeData.dispatchSize;
  51705. } else {
  51706. dispatchSize = dispatchSizeOrCount;
  51707. }
  51708. //
  51709. passEncoderGPU.dispatchWorkgroups(
  51710. dispatchSize[ 0 ],
  51711. dispatchSize[ 1 ] || 1,
  51712. dispatchSize[ 2 ] || 1
  51713. );
  51714. }
  51715. /**
  51716. * This method is executed at the end of a compute call and
  51717. * finalizes work after compute tasks.
  51718. *
  51719. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  51720. */
  51721. finishCompute( computeGroup ) {
  51722. const groupData = this.get( computeGroup );
  51723. groupData.passEncoderGPU.end();
  51724. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  51725. }
  51726. /**
  51727. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  51728. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  51729. *
  51730. * @async
  51731. * @return {Promise} A Promise that resolves when synchronization has been finished.
  51732. */
  51733. async waitForGPU() {
  51734. await this.device.queue.onSubmittedWorkDone();
  51735. }
  51736. // render object
  51737. /**
  51738. * Executes a draw command for the given render object.
  51739. *
  51740. * @param {RenderObject} renderObject - The render object to draw.
  51741. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  51742. */
  51743. draw( renderObject, info ) {
  51744. const { object, material, context, pipeline } = renderObject;
  51745. const bindings = renderObject.getBindings();
  51746. const renderContextData = this.get( context );
  51747. const pipelineGPU = this.get( pipeline ).pipeline;
  51748. const index = renderObject.getIndex();
  51749. const hasIndex = ( index !== null );
  51750. const drawParams = renderObject.getDrawParameters();
  51751. if ( drawParams === null ) return;
  51752. // pipeline
  51753. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  51754. // pipeline
  51755. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  51756. currentSets.pipeline = pipelineGPU;
  51757. // bind groups
  51758. const currentBindingGroups = currentSets.bindingGroups;
  51759. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  51760. const bindGroup = bindings[ i ];
  51761. const bindingsData = this.get( bindGroup );
  51762. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  51763. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  51764. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  51765. }
  51766. }
  51767. // attributes
  51768. // index
  51769. if ( hasIndex === true ) {
  51770. if ( currentSets.index !== index ) {
  51771. const buffer = this.get( index ).buffer;
  51772. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  51773. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  51774. currentSets.index = index;
  51775. }
  51776. }
  51777. // vertex buffers
  51778. const vertexBuffers = renderObject.getVertexBuffers();
  51779. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  51780. const vertexBuffer = vertexBuffers[ i ];
  51781. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  51782. const buffer = this.get( vertexBuffer ).buffer;
  51783. passEncoderGPU.setVertexBuffer( i, buffer );
  51784. currentSets.attributes[ i ] = vertexBuffer;
  51785. }
  51786. }
  51787. // stencil
  51788. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  51789. passEncoderGPU.setStencilReference( material.stencilRef );
  51790. renderContextData.currentStencilRef = material.stencilRef;
  51791. }
  51792. };
  51793. // Define draw function
  51794. const draw = ( passEncoderGPU, currentSets ) => {
  51795. setPipelineAndBindings( passEncoderGPU, currentSets );
  51796. if ( object.isBatchedMesh === true ) {
  51797. const starts = object._multiDrawStarts;
  51798. const counts = object._multiDrawCounts;
  51799. const drawCount = object._multiDrawCount;
  51800. const drawInstances = object._multiDrawInstances;
  51801. if ( drawInstances !== null ) {
  51802. // @deprecated, r174
  51803. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  51804. }
  51805. for ( let i = 0; i < drawCount; i ++ ) {
  51806. const count = drawInstances ? drawInstances[ i ] : 1;
  51807. const firstInstance = count > 1 ? 0 : i;
  51808. if ( hasIndex === true ) {
  51809. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  51810. } else {
  51811. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  51812. }
  51813. info.update( object, counts[ i ], count );
  51814. }
  51815. } else if ( hasIndex === true ) {
  51816. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  51817. const indirect = renderObject.getIndirect();
  51818. if ( indirect !== null ) {
  51819. const buffer = this.get( indirect ).buffer;
  51820. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  51821. } else {
  51822. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  51823. }
  51824. info.update( object, indexCount, instanceCount );
  51825. } else {
  51826. const { vertexCount, instanceCount, firstVertex } = drawParams;
  51827. const indirect = renderObject.getIndirect();
  51828. if ( indirect !== null ) {
  51829. const buffer = this.get( indirect ).buffer;
  51830. passEncoderGPU.drawIndirect( buffer, 0 );
  51831. } else {
  51832. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  51833. }
  51834. info.update( object, vertexCount, instanceCount );
  51835. }
  51836. };
  51837. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  51838. const cameraData = this.get( renderObject.camera );
  51839. const cameras = renderObject.camera.cameras;
  51840. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  51841. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  51842. const bindingsData = this.get( cameraIndex );
  51843. const indexesGPU = [];
  51844. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  51845. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51846. data[ 0 ] = i;
  51847. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  51848. indexesGPU.push( bindGroupIndex );
  51849. }
  51850. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  51851. }
  51852. const pixelRatio = this.renderer.getPixelRatio();
  51853. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51854. const subCamera = cameras[ i ];
  51855. if ( object.layers.test( subCamera.layers ) ) {
  51856. const vp = subCamera.viewport;
  51857. let pass = renderContextData.currentPass;
  51858. let sets = renderContextData.currentSets;
  51859. if ( renderContextData.bundleEncoders ) {
  51860. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  51861. const bundleSets = renderContextData.bundleSets[ i ];
  51862. pass = bundleEncoder;
  51863. sets = bundleSets;
  51864. }
  51865. if ( vp ) {
  51866. pass.setViewport(
  51867. Math.floor( vp.x * pixelRatio ),
  51868. Math.floor( vp.y * pixelRatio ),
  51869. Math.floor( vp.width * pixelRatio ),
  51870. Math.floor( vp.height * pixelRatio ),
  51871. context.viewportValue.minDepth,
  51872. context.viewportValue.maxDepth
  51873. );
  51874. }
  51875. // Set camera index binding for this layer
  51876. if ( cameraIndex && cameraData.indexesGPU ) {
  51877. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  51878. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  51879. }
  51880. draw( pass, sets );
  51881. }
  51882. }
  51883. } else {
  51884. // Regular single camera rendering
  51885. if ( renderContextData.currentPass ) {
  51886. // Handle occlusion queries
  51887. if ( renderContextData.occlusionQuerySet !== undefined ) {
  51888. const lastObject = renderContextData.lastOcclusionObject;
  51889. if ( lastObject !== object ) {
  51890. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  51891. renderContextData.currentPass.endOcclusionQuery();
  51892. renderContextData.occlusionQueryIndex ++;
  51893. }
  51894. if ( object.occlusionTest === true ) {
  51895. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  51896. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  51897. }
  51898. renderContextData.lastOcclusionObject = object;
  51899. }
  51900. }
  51901. draw( renderContextData.currentPass, renderContextData.currentSets );
  51902. }
  51903. }
  51904. }
  51905. // cache key
  51906. /**
  51907. * Returns `true` if the render pipeline requires an update.
  51908. *
  51909. * @param {RenderObject} renderObject - The render object.
  51910. * @return {boolean} Whether the render pipeline requires an update or not.
  51911. */
  51912. needsRenderUpdate( renderObject ) {
  51913. const data = this.get( renderObject );
  51914. const { object, material } = renderObject;
  51915. const utils = this.utils;
  51916. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  51917. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  51918. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  51919. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  51920. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  51921. let needsUpdate = false;
  51922. if ( data.material !== material || data.materialVersion !== material.version ||
  51923. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  51924. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  51925. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  51926. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  51927. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  51928. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  51929. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  51930. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  51931. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  51932. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  51933. data.primitiveTopology !== primitiveTopology ||
  51934. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  51935. ) {
  51936. data.material = material; data.materialVersion = material.version;
  51937. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  51938. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  51939. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  51940. data.colorWrite = material.colorWrite;
  51941. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  51942. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  51943. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  51944. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  51945. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  51946. data.sampleCount = sampleCount;
  51947. data.colorSpace = colorSpace;
  51948. data.colorFormat = colorFormat;
  51949. data.depthStencilFormat = depthStencilFormat;
  51950. data.primitiveTopology = primitiveTopology;
  51951. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  51952. needsUpdate = true;
  51953. }
  51954. return needsUpdate;
  51955. }
  51956. /**
  51957. * Returns a cache key that is used to identify render pipelines.
  51958. *
  51959. * @param {RenderObject} renderObject - The render object.
  51960. * @return {string} The cache key.
  51961. */
  51962. getRenderCacheKey( renderObject ) {
  51963. const { object, material } = renderObject;
  51964. const utils = this.utils;
  51965. const renderContext = renderObject.context;
  51966. return [
  51967. material.transparent, material.blending, material.premultipliedAlpha,
  51968. material.blendSrc, material.blendDst, material.blendEquation,
  51969. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  51970. material.colorWrite,
  51971. material.depthWrite, material.depthTest, material.depthFunc,
  51972. material.stencilWrite, material.stencilFunc,
  51973. material.stencilFail, material.stencilZFail, material.stencilZPass,
  51974. material.stencilFuncMask, material.stencilWriteMask,
  51975. material.side,
  51976. utils.getSampleCountRenderContext( renderContext ),
  51977. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  51978. utils.getPrimitiveTopology( object, material ),
  51979. renderObject.getGeometryCacheKey(),
  51980. renderObject.clippingContextCacheKey
  51981. ].join();
  51982. }
  51983. // textures
  51984. /**
  51985. * Creates a GPU sampler for the given texture.
  51986. *
  51987. * @param {Texture} texture - The texture to create the sampler for.
  51988. */
  51989. createSampler( texture ) {
  51990. this.textureUtils.createSampler( texture );
  51991. }
  51992. /**
  51993. * Destroys the GPU sampler for the given texture.
  51994. *
  51995. * @param {Texture} texture - The texture to destroy the sampler for.
  51996. */
  51997. destroySampler( texture ) {
  51998. this.textureUtils.destroySampler( texture );
  51999. }
  52000. /**
  52001. * Creates a default texture for the given texture that can be used
  52002. * as a placeholder until the actual texture is ready for usage.
  52003. *
  52004. * @param {Texture} texture - The texture to create a default texture for.
  52005. */
  52006. createDefaultTexture( texture ) {
  52007. this.textureUtils.createDefaultTexture( texture );
  52008. }
  52009. /**
  52010. * Defines a texture on the GPU for the given texture object.
  52011. *
  52012. * @param {Texture} texture - The texture.
  52013. * @param {Object} [options={}] - Optional configuration parameter.
  52014. */
  52015. createTexture( texture, options ) {
  52016. this.textureUtils.createTexture( texture, options );
  52017. }
  52018. /**
  52019. * Uploads the updated texture data to the GPU.
  52020. *
  52021. * @param {Texture} texture - The texture.
  52022. * @param {Object} [options={}] - Optional configuration parameter.
  52023. */
  52024. updateTexture( texture, options ) {
  52025. this.textureUtils.updateTexture( texture, options );
  52026. }
  52027. /**
  52028. * Generates mipmaps for the given texture.
  52029. *
  52030. * @param {Texture} texture - The texture.
  52031. */
  52032. generateMipmaps( texture ) {
  52033. this.textureUtils.generateMipmaps( texture );
  52034. }
  52035. /**
  52036. * Destroys the GPU data for the given texture object.
  52037. *
  52038. * @param {Texture} texture - The texture.
  52039. */
  52040. destroyTexture( texture ) {
  52041. this.textureUtils.destroyTexture( texture );
  52042. }
  52043. /**
  52044. * Returns texture data as a typed array.
  52045. *
  52046. * @async
  52047. * @param {Texture} texture - The texture to copy.
  52048. * @param {number} x - The x coordinate of the copy origin.
  52049. * @param {number} y - The y coordinate of the copy origin.
  52050. * @param {number} width - The width of the copy.
  52051. * @param {number} height - The height of the copy.
  52052. * @param {number} faceIndex - The face index.
  52053. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  52054. */
  52055. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  52056. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  52057. }
  52058. /**
  52059. * Inits a time stamp query for the given render context.
  52060. *
  52061. * @param {RenderContext} renderContext - The render context.
  52062. * @param {Object} descriptor - The query descriptor.
  52063. */
  52064. initTimestampQuery( renderContext, descriptor ) {
  52065. if ( ! this.trackTimestamp ) return;
  52066. const type = renderContext.isComputeNode ? 'compute' : 'render';
  52067. if ( ! this.timestampQueryPool[ type ] ) {
  52068. // TODO: Variable maxQueries?
  52069. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  52070. }
  52071. const timestampQueryPool = this.timestampQueryPool[ type ];
  52072. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  52073. descriptor.timestampWrites = {
  52074. querySet: timestampQueryPool.querySet,
  52075. beginningOfPassWriteIndex: baseOffset,
  52076. endOfPassWriteIndex: baseOffset + 1,
  52077. };
  52078. }
  52079. // node builder
  52080. /**
  52081. * Returns a node builder for the given render object.
  52082. *
  52083. * @param {RenderObject} object - The render object.
  52084. * @param {Renderer} renderer - The renderer.
  52085. * @return {WGSLNodeBuilder} The node builder.
  52086. */
  52087. createNodeBuilder( object, renderer ) {
  52088. return new WGSLNodeBuilder( object, renderer );
  52089. }
  52090. // program
  52091. /**
  52092. * Creates a shader program from the given programmable stage.
  52093. *
  52094. * @param {ProgrammableStage} program - The programmable stage.
  52095. */
  52096. createProgram( program ) {
  52097. const programGPU = this.get( program );
  52098. programGPU.module = {
  52099. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  52100. entryPoint: 'main'
  52101. };
  52102. }
  52103. /**
  52104. * Destroys the shader program of the given programmable stage.
  52105. *
  52106. * @param {ProgrammableStage} program - The programmable stage.
  52107. */
  52108. destroyProgram( program ) {
  52109. this.delete( program );
  52110. }
  52111. // pipelines
  52112. /**
  52113. * Creates a render pipeline for the given render object.
  52114. *
  52115. * @param {RenderObject} renderObject - The render object.
  52116. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  52117. */
  52118. createRenderPipeline( renderObject, promises ) {
  52119. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  52120. }
  52121. /**
  52122. * Creates a compute pipeline for the given compute node.
  52123. *
  52124. * @param {ComputePipeline} computePipeline - The compute pipeline.
  52125. * @param {Array<BindGroup>} bindings - The bindings.
  52126. */
  52127. createComputePipeline( computePipeline, bindings ) {
  52128. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  52129. }
  52130. /**
  52131. * Prepares the state for encoding render bundles.
  52132. *
  52133. * @param {RenderContext} renderContext - The render context.
  52134. */
  52135. beginBundle( renderContext ) {
  52136. const renderContextData = this.get( renderContext );
  52137. renderContextData._currentPass = renderContextData.currentPass;
  52138. renderContextData._currentSets = renderContextData.currentSets;
  52139. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  52140. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  52141. }
  52142. /**
  52143. * After processing render bundles this method finalizes related work.
  52144. *
  52145. * @param {RenderContext} renderContext - The render context.
  52146. * @param {RenderBundle} bundle - The render bundle.
  52147. */
  52148. finishBundle( renderContext, bundle ) {
  52149. const renderContextData = this.get( renderContext );
  52150. const bundleEncoder = renderContextData.currentPass;
  52151. const bundleGPU = bundleEncoder.finish();
  52152. this.get( bundle ).bundleGPU = bundleGPU;
  52153. // restore render pass state
  52154. renderContextData.currentSets = renderContextData._currentSets;
  52155. renderContextData.currentPass = renderContextData._currentPass;
  52156. }
  52157. /**
  52158. * Adds a render bundle to the render context data.
  52159. *
  52160. * @param {RenderContext} renderContext - The render context.
  52161. * @param {RenderBundle} bundle - The render bundle to add.
  52162. */
  52163. addBundle( renderContext, bundle ) {
  52164. const renderContextData = this.get( renderContext );
  52165. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  52166. }
  52167. // bindings
  52168. /**
  52169. * Creates bindings from the given bind group definition.
  52170. *
  52171. * @param {BindGroup} bindGroup - The bind group.
  52172. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52173. * @param {number} cacheIndex - The cache index.
  52174. * @param {number} version - The version.
  52175. */
  52176. createBindings( bindGroup, bindings, cacheIndex, version ) {
  52177. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  52178. }
  52179. /**
  52180. * Updates the given bind group definition.
  52181. *
  52182. * @param {BindGroup} bindGroup - The bind group.
  52183. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52184. * @param {number} cacheIndex - The cache index.
  52185. * @param {number} version - The version.
  52186. */
  52187. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  52188. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  52189. }
  52190. /**
  52191. * Updates a buffer binding.
  52192. *
  52193. * @param {Buffer} binding - The buffer binding to update.
  52194. */
  52195. updateBinding( binding ) {
  52196. this.bindingUtils.updateBinding( binding );
  52197. }
  52198. // attributes
  52199. /**
  52200. * Creates the buffer of an indexed shader attribute.
  52201. *
  52202. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  52203. */
  52204. createIndexAttribute( attribute ) {
  52205. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  52206. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  52207. usage |= GPUBufferUsage.STORAGE;
  52208. }
  52209. this.attributeUtils.createAttribute( attribute, usage );
  52210. }
  52211. /**
  52212. * Creates the GPU buffer of a shader attribute.
  52213. *
  52214. * @param {BufferAttribute} attribute - The buffer attribute.
  52215. */
  52216. createAttribute( attribute ) {
  52217. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  52218. }
  52219. /**
  52220. * Creates the GPU buffer of a storage attribute.
  52221. *
  52222. * @param {BufferAttribute} attribute - The buffer attribute.
  52223. */
  52224. createStorageAttribute( attribute ) {
  52225. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  52226. }
  52227. /**
  52228. * Creates the GPU buffer of an indirect storage attribute.
  52229. *
  52230. * @param {BufferAttribute} attribute - The buffer attribute.
  52231. */
  52232. createIndirectStorageAttribute( attribute ) {
  52233. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  52234. }
  52235. /**
  52236. * Updates the GPU buffer of a shader attribute.
  52237. *
  52238. * @param {BufferAttribute} attribute - The buffer attribute to update.
  52239. */
  52240. updateAttribute( attribute ) {
  52241. this.attributeUtils.updateAttribute( attribute );
  52242. }
  52243. /**
  52244. * Destroys the GPU buffer of a shader attribute.
  52245. *
  52246. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  52247. */
  52248. destroyAttribute( attribute ) {
  52249. this.attributeUtils.destroyAttribute( attribute );
  52250. }
  52251. // canvas
  52252. /**
  52253. * Triggers an update of the default render pass descriptor.
  52254. */
  52255. updateSize() {
  52256. this.colorBuffer = this.textureUtils.getColorBuffer();
  52257. this.defaultRenderPassdescriptor = null;
  52258. }
  52259. // utils public
  52260. /**
  52261. * Returns the maximum anisotropy texture filtering value.
  52262. *
  52263. * @return {number} The maximum anisotropy texture filtering value.
  52264. */
  52265. getMaxAnisotropy() {
  52266. return 16;
  52267. }
  52268. /**
  52269. * Checks if the given feature is supported by the backend.
  52270. *
  52271. * @param {string} name - The feature's name.
  52272. * @return {boolean} Whether the feature is supported or not.
  52273. */
  52274. hasFeature( name ) {
  52275. return this.device.features.has( name );
  52276. }
  52277. /**
  52278. * Copies data of the given source texture to the given destination texture.
  52279. *
  52280. * @param {Texture} srcTexture - The source texture.
  52281. * @param {Texture} dstTexture - The destination texture.
  52282. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  52283. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  52284. * @param {number} [srcLevel=0] - The mipmap level to copy.
  52285. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  52286. */
  52287. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  52288. let dstX = 0;
  52289. let dstY = 0;
  52290. let dstZ = 0;
  52291. let srcX = 0;
  52292. let srcY = 0;
  52293. let srcZ = 0;
  52294. let srcWidth = srcTexture.image.width;
  52295. let srcHeight = srcTexture.image.height;
  52296. let srcDepth = 1;
  52297. if ( srcRegion !== null ) {
  52298. if ( srcRegion.isBox3 === true ) {
  52299. srcX = srcRegion.min.x;
  52300. srcY = srcRegion.min.y;
  52301. srcZ = srcRegion.min.z;
  52302. srcWidth = srcRegion.max.x - srcRegion.min.x;
  52303. srcHeight = srcRegion.max.y - srcRegion.min.y;
  52304. srcDepth = srcRegion.max.z - srcRegion.min.z;
  52305. } else {
  52306. // Assume it's a Box2
  52307. srcX = srcRegion.min.x;
  52308. srcY = srcRegion.min.y;
  52309. srcWidth = srcRegion.max.x - srcRegion.min.x;
  52310. srcHeight = srcRegion.max.y - srcRegion.min.y;
  52311. srcDepth = 1;
  52312. }
  52313. }
  52314. if ( dstPosition !== null ) {
  52315. dstX = dstPosition.x;
  52316. dstY = dstPosition.y;
  52317. dstZ = dstPosition.z || 0;
  52318. }
  52319. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  52320. const sourceGPU = this.get( srcTexture ).texture;
  52321. const destinationGPU = this.get( dstTexture ).texture;
  52322. encoder.copyTextureToTexture(
  52323. {
  52324. texture: sourceGPU,
  52325. mipLevel: srcLevel,
  52326. origin: { x: srcX, y: srcY, z: srcZ }
  52327. },
  52328. {
  52329. texture: destinationGPU,
  52330. mipLevel: dstLevel,
  52331. origin: { x: dstX, y: dstY, z: dstZ }
  52332. },
  52333. [
  52334. srcWidth,
  52335. srcHeight,
  52336. srcDepth
  52337. ]
  52338. );
  52339. this.device.queue.submit( [ encoder.finish() ] );
  52340. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  52341. this.textureUtils.generateMipmaps( dstTexture );
  52342. }
  52343. }
  52344. /**
  52345. * Copies the current bound framebuffer to the given texture.
  52346. *
  52347. * @param {Texture} texture - The destination texture.
  52348. * @param {RenderContext} renderContext - The render context.
  52349. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  52350. */
  52351. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  52352. const renderContextData = this.get( renderContext );
  52353. let sourceGPU = null;
  52354. if ( renderContext.renderTarget ) {
  52355. if ( texture.isDepthTexture ) {
  52356. sourceGPU = this.get( renderContext.depthTexture ).texture;
  52357. } else {
  52358. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  52359. }
  52360. } else {
  52361. if ( texture.isDepthTexture ) {
  52362. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  52363. } else {
  52364. sourceGPU = this.context.getCurrentTexture();
  52365. }
  52366. }
  52367. const destinationGPU = this.get( texture ).texture;
  52368. if ( sourceGPU.format !== destinationGPU.format ) {
  52369. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  52370. return;
  52371. }
  52372. let encoder;
  52373. if ( renderContextData.currentPass ) {
  52374. renderContextData.currentPass.end();
  52375. encoder = renderContextData.encoder;
  52376. } else {
  52377. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  52378. }
  52379. encoder.copyTextureToTexture(
  52380. {
  52381. texture: sourceGPU,
  52382. origin: [ rectangle.x, rectangle.y, 0 ],
  52383. },
  52384. {
  52385. texture: destinationGPU
  52386. },
  52387. [
  52388. rectangle.z,
  52389. rectangle.w
  52390. ]
  52391. );
  52392. if ( renderContextData.currentPass ) {
  52393. const { descriptor } = renderContextData;
  52394. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  52395. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  52396. }
  52397. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  52398. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  52399. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  52400. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  52401. if ( renderContext.viewport ) {
  52402. this.updateViewport( renderContext );
  52403. }
  52404. if ( renderContext.scissor ) {
  52405. const { x, y, width, height } = renderContext.scissorValue;
  52406. renderContextData.currentPass.setScissorRect( x, y, width, height );
  52407. }
  52408. } else {
  52409. this.device.queue.submit( [ encoder.finish() ] );
  52410. }
  52411. if ( texture.generateMipmaps ) {
  52412. this.textureUtils.generateMipmaps( texture );
  52413. }
  52414. }
  52415. }
  52416. /**
  52417. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  52418. *
  52419. * @augments SpotLight
  52420. */
  52421. class IESSpotLight extends SpotLight {
  52422. /**
  52423. * Constructs a new IES spot light.
  52424. *
  52425. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  52426. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  52427. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  52428. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  52429. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  52430. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  52431. */
  52432. constructor( color, intensity, distance, angle, penumbra, decay ) {
  52433. super( color, intensity, distance, angle, penumbra, decay );
  52434. /**
  52435. * TODO
  52436. *
  52437. * @type {?Texture}
  52438. * @default null
  52439. */
  52440. this.iesMap = null;
  52441. }
  52442. copy( source, recursive ) {
  52443. super.copy( source, recursive );
  52444. this.iesMap = source.iesMap;
  52445. return this;
  52446. }
  52447. }
  52448. /**
  52449. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  52450. *
  52451. * @augments SpotLight
  52452. */
  52453. class ProjectorLight extends SpotLight {
  52454. /**
  52455. * Constructs a new projector light.
  52456. *
  52457. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  52458. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  52459. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  52460. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  52461. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  52462. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  52463. */
  52464. constructor( color, intensity, distance, angle, penumbra, decay ) {
  52465. super( color, intensity, distance, angle, penumbra, decay );
  52466. /**
  52467. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  52468. *
  52469. * @type {number}
  52470. * @default null
  52471. */
  52472. this.aspect = null;
  52473. }
  52474. copy( source, recursive ) {
  52475. super.copy( source, recursive );
  52476. this.aspect = source.aspect;
  52477. return this;
  52478. }
  52479. }
  52480. /**
  52481. * This version of a node library represents the standard version
  52482. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  52483. * techniques and materials to node-based implementations.
  52484. *
  52485. * @private
  52486. * @augments NodeLibrary
  52487. */
  52488. class StandardNodeLibrary extends NodeLibrary {
  52489. /**
  52490. * Constructs a new standard node library.
  52491. */
  52492. constructor() {
  52493. super();
  52494. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  52495. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  52496. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  52497. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  52498. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  52499. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  52500. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  52501. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  52502. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  52503. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  52504. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  52505. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  52506. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  52507. this.addLight( PointLightNode, PointLight );
  52508. this.addLight( DirectionalLightNode, DirectionalLight );
  52509. this.addLight( RectAreaLightNode, RectAreaLight );
  52510. this.addLight( SpotLightNode, SpotLight );
  52511. this.addLight( AmbientLightNode, AmbientLight );
  52512. this.addLight( HemisphereLightNode, HemisphereLight );
  52513. this.addLight( LightProbeNode, LightProbe );
  52514. this.addLight( IESSpotLightNode, IESSpotLight );
  52515. this.addLight( ProjectorLightNode, ProjectorLight );
  52516. this.addToneMapping( linearToneMapping, LinearToneMapping );
  52517. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  52518. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  52519. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  52520. this.addToneMapping( agxToneMapping, AgXToneMapping );
  52521. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  52522. }
  52523. }
  52524. /*
  52525. const debugHandler = {
  52526. get: function ( target, name ) {
  52527. // Add |update
  52528. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  52529. return target[ name ];
  52530. }
  52531. };
  52532. */
  52533. /**
  52534. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  52535. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  52536. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  52537. *
  52538. * @augments Renderer
  52539. */
  52540. class WebGPURenderer extends Renderer {
  52541. /**
  52542. * WebGPURenderer options.
  52543. *
  52544. * @typedef {Object} WebGPURenderer~Options
  52545. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  52546. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  52547. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  52548. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  52549. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  52550. * @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.
  52551. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  52552. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  52553. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  52554. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  52555. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  52556. */
  52557. /**
  52558. * Constructs a new WebGPU renderer.
  52559. *
  52560. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  52561. */
  52562. constructor( parameters = {} ) {
  52563. let BackendClass;
  52564. if ( parameters.forceWebGL ) {
  52565. BackendClass = WebGLBackend;
  52566. } else {
  52567. BackendClass = WebGPUBackend;
  52568. parameters.getFallback = () => {
  52569. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  52570. return new WebGLBackend( parameters );
  52571. };
  52572. }
  52573. const backend = new BackendClass( parameters );
  52574. //super( new Proxy( backend, debugHandler ) );
  52575. super( backend, parameters );
  52576. /**
  52577. * The generic default value is overwritten with the
  52578. * standard node library for type mapping.
  52579. *
  52580. * @type {StandardNodeLibrary}
  52581. */
  52582. this.library = new StandardNodeLibrary();
  52583. /**
  52584. * This flag can be used for type testing.
  52585. *
  52586. * @type {boolean}
  52587. * @readonly
  52588. * @default true
  52589. */
  52590. this.isWebGPURenderer = true;
  52591. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  52592. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  52593. }
  52594. }
  52595. }
  52596. /**
  52597. * A specialized group which enables applications access to the
  52598. * Render Bundle API of WebGPU. The group with all its descendant nodes
  52599. * are considered as one render bundle and processed as such by
  52600. * the renderer.
  52601. *
  52602. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  52603. * With a WebGL backend, the group can technically be rendered but without
  52604. * any performance improvements.
  52605. *
  52606. * @augments Group
  52607. */
  52608. class BundleGroup extends Group {
  52609. /**
  52610. * Constructs a new bundle group.
  52611. */
  52612. constructor() {
  52613. super();
  52614. /**
  52615. * This flag can be used for type testing.
  52616. *
  52617. * @type {boolean}
  52618. * @readonly
  52619. * @default true
  52620. */
  52621. this.isBundleGroup = true;
  52622. /**
  52623. * This property is only relevant for detecting types
  52624. * during serialization/deserialization. It should always
  52625. * match the class name.
  52626. *
  52627. * @type {string}
  52628. * @readonly
  52629. * @default 'BundleGroup'
  52630. */
  52631. this.type = 'BundleGroup';
  52632. /**
  52633. * Whether the bundle is static or not. When set to `true`, the structure
  52634. * is assumed to be static and does not change. E.g. no new objects are
  52635. * added to the group
  52636. *
  52637. * If a change is required, an update can still be forced by setting the
  52638. * `needsUpdate` flag to `true`.
  52639. *
  52640. * @type {boolean}
  52641. * @default true
  52642. */
  52643. this.static = true;
  52644. /**
  52645. * The bundle group's version.
  52646. *
  52647. * @type {number}
  52648. * @readonly
  52649. * @default 0
  52650. */
  52651. this.version = 0;
  52652. }
  52653. /**
  52654. * Set this property to `true` when the bundle group has changed.
  52655. *
  52656. * @type {boolean}
  52657. * @default false
  52658. * @param {boolean} value
  52659. */
  52660. set needsUpdate( value ) {
  52661. if ( value === true ) this.version ++;
  52662. }
  52663. }
  52664. /**
  52665. * This module is responsible to manage the post processing setups in apps.
  52666. * You usually create a single instance of this class and use it to define
  52667. * the output of your post processing effect chain.
  52668. * ```js
  52669. * const postProcessing = new PostProcessing( renderer );
  52670. *
  52671. * const scenePass = pass( scene, camera );
  52672. *
  52673. * postProcessing.outputNode = scenePass;
  52674. * ```
  52675. *
  52676. * Note: This module can only be used with `WebGPURenderer`.
  52677. */
  52678. class PostProcessing {
  52679. /**
  52680. * Constructs a new post processing management module.
  52681. *
  52682. * @param {Renderer} renderer - A reference to the renderer.
  52683. * @param {Node<vec4>} outputNode - An optional output node.
  52684. */
  52685. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  52686. /**
  52687. * A reference to the renderer.
  52688. *
  52689. * @type {Renderer}
  52690. */
  52691. this.renderer = renderer;
  52692. /**
  52693. * A node which defines the final output of the post
  52694. * processing. This is usually the last node in a chain
  52695. * of effect nodes.
  52696. *
  52697. * @type {Node<vec4>}
  52698. */
  52699. this.outputNode = outputNode;
  52700. /**
  52701. * Whether the default output tone mapping and color
  52702. * space transformation should be enabled or not.
  52703. *
  52704. * It is enabled by default by it must be disabled when
  52705. * effects must be executed after tone mapping and color
  52706. * space conversion. A typical example is FXAA which
  52707. * requires sRGB input.
  52708. *
  52709. * When set to `false`, the app must control the output
  52710. * transformation with `RenderOutputNode`.
  52711. *
  52712. * ```js
  52713. * const outputPass = renderOutput( scenePass );
  52714. * ```
  52715. *
  52716. * @type {boolean}
  52717. */
  52718. this.outputColorTransform = true;
  52719. /**
  52720. * Must be set to `true` when the output node changes.
  52721. *
  52722. * @type {Node<vec4>}
  52723. */
  52724. this.needsUpdate = true;
  52725. const material = new NodeMaterial();
  52726. material.name = 'PostProcessing';
  52727. /**
  52728. * The full screen quad that is used to render
  52729. * the effects.
  52730. *
  52731. * @private
  52732. * @type {QuadMesh}
  52733. */
  52734. this._quadMesh = new QuadMesh( material );
  52735. /**
  52736. * The context of the post processing stack.
  52737. *
  52738. * @private
  52739. * @type {?Object}
  52740. * @default null
  52741. */
  52742. this._context = null;
  52743. }
  52744. /**
  52745. * When `PostProcessing` is used to apply post processing effects,
  52746. * the application must use this version of `render()` inside
  52747. * its animation loop (not the one from the renderer).
  52748. */
  52749. render() {
  52750. const renderer = this.renderer;
  52751. this._update();
  52752. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  52753. const toneMapping = renderer.toneMapping;
  52754. const outputColorSpace = renderer.outputColorSpace;
  52755. renderer.toneMapping = NoToneMapping;
  52756. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  52757. //
  52758. const currentXR = renderer.xr.enabled;
  52759. renderer.xr.enabled = false;
  52760. this._quadMesh.render( renderer );
  52761. renderer.xr.enabled = currentXR;
  52762. //
  52763. renderer.toneMapping = toneMapping;
  52764. renderer.outputColorSpace = outputColorSpace;
  52765. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  52766. }
  52767. /**
  52768. * Returns the current context of the post processing stack.
  52769. *
  52770. * @readonly
  52771. * @type {?Object}
  52772. */
  52773. get context() {
  52774. return this._context;
  52775. }
  52776. /**
  52777. * Frees internal resources.
  52778. */
  52779. dispose() {
  52780. this._quadMesh.material.dispose();
  52781. }
  52782. /**
  52783. * Updates the state of the module.
  52784. *
  52785. * @private
  52786. */
  52787. _update() {
  52788. if ( this.needsUpdate === true ) {
  52789. const renderer = this.renderer;
  52790. const toneMapping = renderer.toneMapping;
  52791. const outputColorSpace = renderer.outputColorSpace;
  52792. const context = {
  52793. postProcessing: this,
  52794. onBeforePostProcessing: null,
  52795. onAfterPostProcessing: null
  52796. };
  52797. let outputNode = this.outputNode;
  52798. if ( this.outputColorTransform === true ) {
  52799. outputNode = outputNode.context( context );
  52800. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  52801. } else {
  52802. context.toneMapping = toneMapping;
  52803. context.outputColorSpace = outputColorSpace;
  52804. outputNode = outputNode.context( context );
  52805. }
  52806. this._context = context;
  52807. this._quadMesh.material.fragmentNode = outputNode;
  52808. this._quadMesh.material.needsUpdate = true;
  52809. this.needsUpdate = false;
  52810. }
  52811. }
  52812. /**
  52813. * When `PostProcessing` is used to apply post processing effects,
  52814. * the application must use this version of `renderAsync()` inside
  52815. * its animation loop (not the one from the renderer).
  52816. *
  52817. * @async
  52818. * @return {Promise} A Promise that resolves when the render has been finished.
  52819. */
  52820. async renderAsync() {
  52821. this._update();
  52822. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  52823. const renderer = this.renderer;
  52824. const toneMapping = renderer.toneMapping;
  52825. const outputColorSpace = renderer.outputColorSpace;
  52826. renderer.toneMapping = NoToneMapping;
  52827. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  52828. //
  52829. const currentXR = renderer.xr.enabled;
  52830. renderer.xr.enabled = false;
  52831. await this._quadMesh.renderAsync( renderer );
  52832. renderer.xr.enabled = currentXR;
  52833. //
  52834. renderer.toneMapping = toneMapping;
  52835. renderer.outputColorSpace = outputColorSpace;
  52836. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  52837. }
  52838. }
  52839. /**
  52840. * This special type of texture is intended for compute shaders.
  52841. * It can be used to compute the data of a texture with a compute shader.
  52842. *
  52843. * Note: This type of texture can only be used with `WebGPURenderer`
  52844. * and a WebGPU backend.
  52845. *
  52846. * @augments Texture
  52847. */
  52848. class StorageTexture extends Texture {
  52849. /**
  52850. * Constructs a new storage texture.
  52851. *
  52852. * @param {number} [width=1] - The storage texture's width.
  52853. * @param {number} [height=1] - The storage texture's height.
  52854. */
  52855. constructor( width = 1, height = 1 ) {
  52856. super();
  52857. /**
  52858. * The image object which just represents the texture's dimension.
  52859. *
  52860. * @type {{width: number, height: number}}
  52861. */
  52862. this.image = { width, height };
  52863. /**
  52864. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  52865. *
  52866. * @type {number}
  52867. */
  52868. this.magFilter = LinearFilter;
  52869. /**
  52870. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  52871. *
  52872. * @type {number}
  52873. */
  52874. this.minFilter = LinearFilter;
  52875. /**
  52876. * This flag can be used for type testing.
  52877. *
  52878. * @type {boolean}
  52879. * @readonly
  52880. * @default true
  52881. */
  52882. this.isStorageTexture = true;
  52883. }
  52884. /**
  52885. * Sets the size of the storage texture.
  52886. *
  52887. * @param {number} width - The new width of the storage texture.
  52888. * @param {number} height - The new height of the storage texture.
  52889. */
  52890. setSize( width, height ) {
  52891. if ( this.image.width !== width || this.image.height !== height ) {
  52892. this.image.width = width;
  52893. this.image.height = height;
  52894. this.dispose();
  52895. }
  52896. }
  52897. }
  52898. /**
  52899. * This special type of texture is intended for compute shaders.
  52900. * It can be used to compute the data of a texture with a compute shader.
  52901. *
  52902. * Note: This type of texture can only be used with `WebGPURenderer`
  52903. * and a WebGPU backend.
  52904. *
  52905. * @augments Texture
  52906. */
  52907. class Storage3DTexture extends Texture {
  52908. /**
  52909. * Constructs a new storage texture.
  52910. *
  52911. * @param {number} [width=1] - The storage texture's width.
  52912. * @param {number} [height=1] - The storage texture's height.
  52913. * @param {number} [depth=1] - The storage texture's depth.
  52914. */
  52915. constructor( width = 1, height = 1, depth = 1 ) {
  52916. super();
  52917. //inherited from texture. Must be false for 3DTexture
  52918. this.isArrayTexture = false;
  52919. /**
  52920. * The image object which just represents the texture's dimension.
  52921. *
  52922. * @type {{width: number, height: number, depth: number}}
  52923. */
  52924. this.image = { width, height, depth };
  52925. /**
  52926. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  52927. *
  52928. * @type {number}
  52929. */
  52930. this.magFilter = LinearFilter;
  52931. /**
  52932. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  52933. *
  52934. * @type {number}
  52935. */
  52936. this.minFilter = LinearFilter;
  52937. /**
  52938. * This defines how the texture is wrapped in the depth direction and corresponds to
  52939. * *W* in UVW mapping.
  52940. *
  52941. * @type {number}
  52942. */
  52943. this.wrapR = ClampToEdgeWrapping;
  52944. /**
  52945. * This flag can be used for type testing.
  52946. *
  52947. * @type {boolean}
  52948. * @readonly
  52949. * @default true
  52950. */
  52951. this.isStorageTexture = true;
  52952. /**
  52953. * Indicates whether this texture is a 3D texture.
  52954. *
  52955. * @type {boolean}
  52956. *
  52957. */
  52958. this.is3DTexture = true;
  52959. }
  52960. /**
  52961. * Sets the size of the storage 3d texture.
  52962. *
  52963. * @param {number} width - The new width of the storage texture.
  52964. * @param {number} height - The new height of the storage texture.
  52965. * @param {number} depth - The new depth of the storage texture.
  52966. */
  52967. setSize( width, height, depth ) {
  52968. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  52969. this.image.width = width;
  52970. this.image.height = height;
  52971. this.image.depth = depth;
  52972. this.dispose();
  52973. }
  52974. }
  52975. }
  52976. /**
  52977. * This special type of texture is intended for compute shaders.
  52978. * It can be used to compute the data of a texture with a compute shader.
  52979. *
  52980. * Note: This type of texture can only be used with `WebGPURenderer`
  52981. * and a WebGPU backend.
  52982. *
  52983. * @augments Texture
  52984. */
  52985. class StorageArrayTexture extends Texture {
  52986. /**
  52987. * Constructs a new storage texture.
  52988. *
  52989. * @param {number} [width=1] - The storage texture's width.
  52990. * @param {number} [height=1] - The storage texture's height.
  52991. * @param {number} [depth=1] - The storage texture's depth.
  52992. */
  52993. constructor( width = 1, height = 1, depth = 1 ) {
  52994. super();
  52995. //inherited from texture
  52996. this.isArrayTexture = true;
  52997. /**
  52998. * The image object which just represents the texture's dimension.
  52999. *
  53000. * @type {{width: number, height: number, depth: number}}
  53001. */
  53002. this.image = { width, height, depth };
  53003. /**
  53004. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  53005. *
  53006. * @type {number}
  53007. */
  53008. this.magFilter = LinearFilter;
  53009. /**
  53010. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  53011. *
  53012. * @type {number}
  53013. */
  53014. this.minFilter = LinearFilter;
  53015. /**
  53016. * This flag can be used for type testing.
  53017. *
  53018. * @type {boolean}
  53019. * @readonly
  53020. * @default true
  53021. */
  53022. this.isStorageTexture = true;
  53023. }
  53024. /**
  53025. * Sets the size of the storage array texture.
  53026. *
  53027. * @param {number} width - The new width of the storage texture.
  53028. * @param {number} height - The new height of the storage texture.
  53029. * @param {number} depth - The new depth of the storage texture.
  53030. */
  53031. setSize( width, height, depth ) {
  53032. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  53033. this.image.width = width;
  53034. this.image.height = height;
  53035. this.image.depth = depth;
  53036. this.dispose();
  53037. }
  53038. }
  53039. }
  53040. /**
  53041. * This special type of buffer attribute is intended for compute shaders.
  53042. * It can be used to encode draw parameters for indirect draw calls.
  53043. *
  53044. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  53045. * and a WebGPU backend.
  53046. *
  53047. * @augments StorageBufferAttribute
  53048. */
  53049. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  53050. /**
  53051. * Constructs a new storage buffer attribute.
  53052. *
  53053. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  53054. * The subsequent parameter is then obsolete.
  53055. * @param {number} itemSize - The item size.
  53056. */
  53057. constructor( count, itemSize ) {
  53058. super( count, itemSize, Uint32Array );
  53059. /**
  53060. * This flag can be used for type testing.
  53061. *
  53062. * @type {boolean}
  53063. * @readonly
  53064. * @default true
  53065. */
  53066. this.isIndirectStorageBufferAttribute = true;
  53067. }
  53068. }
  53069. /**
  53070. * A loader for loading node objects in the three.js JSON Object/Scene format.
  53071. *
  53072. * @augments Loader
  53073. */
  53074. class NodeLoader extends Loader {
  53075. /**
  53076. * Constructs a new node loader.
  53077. *
  53078. * @param {LoadingManager} [manager] - A reference to a loading manager.
  53079. */
  53080. constructor( manager ) {
  53081. super( manager );
  53082. /**
  53083. * Represents a dictionary of textures.
  53084. *
  53085. * @type {Object<string,Texture>}
  53086. */
  53087. this.textures = {};
  53088. /**
  53089. * Represents a dictionary of node types.
  53090. *
  53091. * @type {Object<string,Node.constructor>}
  53092. */
  53093. this.nodes = {};
  53094. }
  53095. /**
  53096. * Loads the node definitions from the given URL.
  53097. *
  53098. * @param {string} url - The path/URL of the file to be loaded.
  53099. * @param {Function} onLoad - Will be called when load completes.
  53100. * @param {Function} onProgress - Will be called while load progresses.
  53101. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  53102. */
  53103. load( url, onLoad, onProgress, onError ) {
  53104. const loader = new FileLoader( this.manager );
  53105. loader.setPath( this.path );
  53106. loader.setRequestHeader( this.requestHeader );
  53107. loader.setWithCredentials( this.withCredentials );
  53108. loader.load( url, ( text ) => {
  53109. try {
  53110. onLoad( this.parse( JSON.parse( text ) ) );
  53111. } catch ( e ) {
  53112. if ( onError ) {
  53113. onError( e );
  53114. } else {
  53115. console.error( e );
  53116. }
  53117. this.manager.itemError( url );
  53118. }
  53119. }, onProgress, onError );
  53120. }
  53121. /**
  53122. * Parse the node dependencies for the loaded node.
  53123. *
  53124. * @param {Array<Object>} [json] - The JSON definition
  53125. * @return {Object<string,Node>} A dictionary with node dependencies.
  53126. */
  53127. parseNodes( json ) {
  53128. const nodes = {};
  53129. if ( json !== undefined ) {
  53130. for ( const nodeJSON of json ) {
  53131. const { uuid, type } = nodeJSON;
  53132. nodes[ uuid ] = this.createNodeFromType( type );
  53133. nodes[ uuid ].uuid = uuid;
  53134. }
  53135. const meta = { nodes, textures: this.textures };
  53136. for ( const nodeJSON of json ) {
  53137. nodeJSON.meta = meta;
  53138. const node = nodes[ nodeJSON.uuid ];
  53139. node.deserialize( nodeJSON );
  53140. delete nodeJSON.meta;
  53141. }
  53142. }
  53143. return nodes;
  53144. }
  53145. /**
  53146. * Parses the node from the given JSON.
  53147. *
  53148. * @param {Object} json - The JSON definition
  53149. * @param {string} json.type - The node type.
  53150. * @param {string} json.uuid - The node UUID.
  53151. * @param {Array<Object>} [json.nodes] - The node dependencies.
  53152. * @param {Object} [json.meta] - The meta data.
  53153. * @return {Node} The parsed node.
  53154. */
  53155. parse( json ) {
  53156. const node = this.createNodeFromType( json.type );
  53157. node.uuid = json.uuid;
  53158. const nodes = this.parseNodes( json.nodes );
  53159. const meta = { nodes, textures: this.textures };
  53160. json.meta = meta;
  53161. node.deserialize( json );
  53162. delete json.meta;
  53163. return node;
  53164. }
  53165. /**
  53166. * Defines the dictionary of textures.
  53167. *
  53168. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  53169. * @return {NodeLoader} A reference to this loader.
  53170. */
  53171. setTextures( value ) {
  53172. this.textures = value;
  53173. return this;
  53174. }
  53175. /**
  53176. * Defines the dictionary of node types.
  53177. *
  53178. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  53179. * @return {NodeLoader} A reference to this loader.
  53180. */
  53181. setNodes( value ) {
  53182. this.nodes = value;
  53183. return this;
  53184. }
  53185. /**
  53186. * Creates a node object from the given type.
  53187. *
  53188. * @param {string} type - The node type.
  53189. * @return {Node} The created node instance.
  53190. */
  53191. createNodeFromType( type ) {
  53192. if ( this.nodes[ type ] === undefined ) {
  53193. console.error( 'THREE.NodeLoader: Node type not found:', type );
  53194. return float();
  53195. }
  53196. return nodeObject( new this.nodes[ type ]() );
  53197. }
  53198. }
  53199. /**
  53200. * A special type of material loader for loading node materials.
  53201. *
  53202. * @augments MaterialLoader
  53203. */
  53204. class NodeMaterialLoader extends MaterialLoader {
  53205. /**
  53206. * Constructs a new node material loader.
  53207. *
  53208. * @param {LoadingManager} [manager] - A reference to a loading manager.
  53209. */
  53210. constructor( manager ) {
  53211. super( manager );
  53212. /**
  53213. * Represents a dictionary of node types.
  53214. *
  53215. * @type {Object<string,Node.constructor>}
  53216. */
  53217. this.nodes = {};
  53218. /**
  53219. * Represents a dictionary of node material types.
  53220. *
  53221. * @type {Object<string,NodeMaterial.constructor>}
  53222. */
  53223. this.nodeMaterials = {};
  53224. }
  53225. /**
  53226. * Parses the node material from the given JSON.
  53227. *
  53228. * @param {Object} json - The JSON definition
  53229. * @return {NodeMaterial}. The parsed material.
  53230. */
  53231. parse( json ) {
  53232. const material = super.parse( json );
  53233. const nodes = this.nodes;
  53234. const inputNodes = json.inputNodes;
  53235. for ( const property in inputNodes ) {
  53236. const uuid = inputNodes[ property ];
  53237. material[ property ] = nodes[ uuid ];
  53238. }
  53239. return material;
  53240. }
  53241. /**
  53242. * Defines the dictionary of node types.
  53243. *
  53244. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  53245. * @return {NodeLoader} A reference to this loader.
  53246. */
  53247. setNodes( value ) {
  53248. this.nodes = value;
  53249. return this;
  53250. }
  53251. /**
  53252. * Defines the dictionary of node material types.
  53253. *
  53254. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  53255. * @return {NodeLoader} A reference to this loader.
  53256. */
  53257. setNodeMaterials( value ) {
  53258. this.nodeMaterials = value;
  53259. return this;
  53260. }
  53261. /**
  53262. * Creates a node material from the given type.
  53263. *
  53264. * @param {string} type - The node material type.
  53265. * @return {Node} The created node material instance.
  53266. */
  53267. createMaterialFromType( type ) {
  53268. const materialClass = this.nodeMaterials[ type ];
  53269. if ( materialClass !== undefined ) {
  53270. return new materialClass();
  53271. }
  53272. return super.createMaterialFromType( type );
  53273. }
  53274. }
  53275. /**
  53276. * A special type of object loader for loading 3D objects using
  53277. * node materials.
  53278. *
  53279. * @augments ObjectLoader
  53280. */
  53281. class NodeObjectLoader extends ObjectLoader {
  53282. /**
  53283. * Constructs a new node object loader.
  53284. *
  53285. * @param {LoadingManager} [manager] - A reference to a loading manager.
  53286. */
  53287. constructor( manager ) {
  53288. super( manager );
  53289. /**
  53290. * Represents a dictionary of node types.
  53291. *
  53292. * @type {Object<string,Node.constructor>}
  53293. */
  53294. this.nodes = {};
  53295. /**
  53296. * Represents a dictionary of node material types.
  53297. *
  53298. * @type {Object<string,NodeMaterial.constructor>}
  53299. */
  53300. this.nodeMaterials = {};
  53301. /**
  53302. * A reference to hold the `nodes` JSON property.
  53303. *
  53304. * @private
  53305. * @type {?Object[]}
  53306. */
  53307. this._nodesJSON = null;
  53308. }
  53309. /**
  53310. * Defines the dictionary of node types.
  53311. *
  53312. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  53313. * @return {NodeObjectLoader} A reference to this loader.
  53314. */
  53315. setNodes( value ) {
  53316. this.nodes = value;
  53317. return this;
  53318. }
  53319. /**
  53320. * Defines the dictionary of node material types.
  53321. *
  53322. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  53323. * @return {NodeObjectLoader} A reference to this loader.
  53324. */
  53325. setNodeMaterials( value ) {
  53326. this.nodeMaterials = value;
  53327. return this;
  53328. }
  53329. /**
  53330. * Parses the node objects from the given JSON.
  53331. *
  53332. * @param {Object} json - The JSON definition
  53333. * @param {Function} onLoad - The onLoad callback function.
  53334. * @return {Object3D}. The parsed 3D object.
  53335. */
  53336. parse( json, onLoad ) {
  53337. this._nodesJSON = json.nodes;
  53338. const data = super.parse( json, onLoad );
  53339. this._nodesJSON = null; // dispose
  53340. return data;
  53341. }
  53342. /**
  53343. * Parses the node objects from the given JSON and textures.
  53344. *
  53345. * @param {Object[]} json - The JSON definition
  53346. * @param {Object<string,Texture>} textures - The texture library.
  53347. * @return {Object<string,Node>}. The parsed nodes.
  53348. */
  53349. parseNodes( json, textures ) {
  53350. if ( json !== undefined ) {
  53351. const loader = new NodeLoader();
  53352. loader.setNodes( this.nodes );
  53353. loader.setTextures( textures );
  53354. return loader.parseNodes( json );
  53355. }
  53356. return {};
  53357. }
  53358. /**
  53359. * Parses the node objects from the given JSON and textures.
  53360. *
  53361. * @param {Object} json - The JSON definition
  53362. * @param {Object<string,Texture>} textures - The texture library.
  53363. * @return {Object<string,NodeMaterial>}. The parsed materials.
  53364. */
  53365. parseMaterials( json, textures ) {
  53366. const materials = {};
  53367. if ( json !== undefined ) {
  53368. const nodes = this.parseNodes( this._nodesJSON, textures );
  53369. const loader = new NodeMaterialLoader();
  53370. loader.setTextures( textures );
  53371. loader.setNodes( nodes );
  53372. loader.setNodeMaterials( this.nodeMaterials );
  53373. for ( let i = 0, l = json.length; i < l; i ++ ) {
  53374. const data = json[ i ];
  53375. materials[ data.uuid ] = loader.parse( data );
  53376. }
  53377. }
  53378. return materials;
  53379. }
  53380. }
  53381. /**
  53382. * In earlier three.js versions, clipping was defined globally
  53383. * on the renderer or on material level. This special version of
  53384. * `THREE.Group` allows to encode the clipping state into the scene
  53385. * graph. Meaning if you create an instance of this group, all
  53386. * descendant 3D objects will be affected by the respective clipping
  53387. * planes.
  53388. *
  53389. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  53390. *
  53391. * @augments Group
  53392. */
  53393. class ClippingGroup extends Group {
  53394. /**
  53395. * Constructs a new clipping group.
  53396. */
  53397. constructor() {
  53398. super();
  53399. /**
  53400. * This flag can be used for type testing.
  53401. *
  53402. * @type {boolean}
  53403. * @readonly
  53404. * @default true
  53405. */
  53406. this.isClippingGroup = true;
  53407. /**
  53408. * An array with clipping planes.
  53409. *
  53410. * @type {Array<Plane>}
  53411. */
  53412. this.clippingPlanes = [];
  53413. /**
  53414. * Whether clipping should be enabled or not.
  53415. *
  53416. * @type {boolean}
  53417. * @default true
  53418. */
  53419. this.enabled = true;
  53420. /**
  53421. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  53422. *
  53423. * @type {boolean}
  53424. * @default false
  53425. */
  53426. this.clipIntersection = false;
  53427. /**
  53428. * Whether shadows should be clipped or not.
  53429. *
  53430. * @type {boolean}
  53431. * @default false
  53432. */
  53433. this.clipShadows = false;
  53434. }
  53435. }
  53436. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, EventNode, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FrustumArray, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoopNode, MRTNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, Storage3DTexture, StorageArrayElementNode, StorageArrayTexture, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号